我有一个
当应用程序启动时,操作栏标题为
为什么应用程序启动时操作栏标题会被设置为
图片:第一张图片是应用程序启动时的AFragment,第二张图片是导航到BFragment,第三张图片是从BFragment返回到AFragment。
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>
And 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
。为什么应用程序启动时操作栏标题会被设置为
application
android:label
,而不是在nav graph中定义的android:label
?我意识到我可以在片段中调用requireActivity().setTitle()
来在运行时管理此问题,但我觉得使用导航图中的android:label
应该已经足够了。图片:第一张图片是应用程序启动时的AFragment,第二张图片是导航到BFragment,第三张图片是从BFragment返回到AFragment。
onSupportNavigateUp()
。一旦我做到了,现在一切都按预期工作了,感谢您的帮助! - Johnas NellenonSupportNavigateUp()
方法? - Gabriele Mariotti