android xml 生成一个 左上角返回箭头
时间: 2024-01-21 09:02:20 浏览: 28
你可以通过在布局文件中添加一个 Toolbar 控件,并在其中设置一个返回按钮来实现左上角返回箭头。
以下是一个示例布局文件代码:
```xml
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</com.google.android.material.appbar.AppBarLayout>
<!-- Your other views here -->
</androidx.coordinatorlayout.widget.CoordinatorLayout>
```
然后,在你的 Activity 中,你可以使用以下代码来添加返回按钮,并在点击时关闭当前 Activity:
```java
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
```
这样就可以在左上角添加一个返回箭头,并在点击时关闭当前 Activity。