【发布时间】:2020-07-17 21:24:52
【问题描述】:
我有一个MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val navController = findNavController(R.id.nav_host_fragment)
toolbar.setupWithNavController(navController, AppBarConfiguration(navController.graph))
}
}
和导航图
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph_main.xml"
app:startDestination="@id/AFragment">
<fragment
android:id="@+id/AFragment"
android:name="com.example.actionbartitletest.AFragment"
android:label="Fragment A"
tools:layout="@layout/fragment_a" >
<action
android:id="@+id/action_AFragment_to_BFragment"
app:destination="@id/BFragment" />
</fragment>
<fragment
android:id="@+id/BFragment"
android:name="com.example.actionbartitletest.BFragment"
android:label="Fragment B"
tools:layout="@layout/fragment_b" />
</navigation>
还有Manifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
还有strings.xml
<resources>
<string name="app_name">ActionBarTitleTest</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
</resources>
当应用程序启动时,操作栏标题是 ActionBarTitleTest(大概是在 Manifest.xml 中定义的 application android:label),但是我希望操作栏标题是 Fragment A,因为它在导航图的android:label 属性。当我从 AFragment -> BFragment 导航时,BFragment 上的操作栏标题按预期为 Fragment B,当我从 BFragment -> AFragment 导航返回时,操作栏标题按预期显示为 Fragment A。
为什么应用程序启动时操作栏标题设置为applicationandroid:label,而不是导航图中定义的android:label?我意识到我可以在运行时通过在片段中调用requireActivity().setTitle() 来管理它,但我觉得使用导航图中的android:label 就足够了。
【问题讨论】:
标签: android android-actionbar androidx android-architecture-navigation android-jetpack-navigation