【发布时间】:2020-08-05 07:00:48
【问题描述】:
我想制作一个自定义工具栏,我可以添加两个或更多按钮来导航其他部分(如配置文件和通知区域)和当前片段名称。如果我用户更改片段并转到另一个地方,向上按钮消失并返回到最后一个地方。现在我尝试这样处理:
appbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appNs="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimaryDark"
android:id="@+id/toolbar"
android:paddingStart="20dp"
android:layoutDirection="rtl"
android:paddingEnd="10dp"
android:theme="@style/toolbarTheme">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="my app name"
android:layout_gravity = "center"
android:textSize="18sp"
android:fontFamily="@font/main_bold"
android:id="@+id/toolbar_title" />
<ImageView
android:id="@+id/imgProfile"
android:src="@drawable/ic_profile"
android:layout_marginStart="15dp"
android:layout_gravity="end"
android:layout_width="25dp"
android:layout_height="25dp"/>
<ImageView
android:id="@+id/imgNotification"
android:src="@drawable/ic_notification"
android:layout_width="25dp"
android:layout_gravity="end"
android:layout_marginStart="15dp"
android:layout_height="25dp"/>
</androidx.appcompat.widget.Toolbar>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/appbar" />
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/myNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/navigation" />
</androidx.core.widget.NestedScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.kt:
setSupportActionBar(toolbar)
val navController = findNavController(R.id.myNavHostFragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
toolbar.setupWithNavController(navController, appBarConfiguration)
如何为 appbar.xml 中定义的 ImageView 设置 onClickListener?
以及如何使标签片段文本可自定义?例如更改字体文本大小和文本颜色以及...
(现在当我进入一个片段时,用户向上按钮返回标签片段将转到边缘或消失并从工具栏部分退出)
【问题讨论】:
标签: android toolbar android-architecture-navigation appbar