第一个活动
class MainActivity : AppCompatActivity() {
private lateinit var navHostFragment: NavHostFragment
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var navController: NavController
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(setOf(R.id.fragment))
setupActionBarWithNavController(navController, appBarConfiguration)
navController.navigate(R.id.secondActivity, SecondActivityArgs(someId = "test").toBundle())
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
第二个活动
class SecondActivity : AppCompatActivity() {
private lateinit var navHostFragment: NavHostFragment
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var navController: NavController
private lateinit var binding: ActivitySecondBinding
private val args: SecondActivityArgs by navArgs()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_second)
binding.lifecycleOwner = this
val someId = args.someId
navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(emptySet())
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
货单
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity"
android:exported="true" />
当我在第二个活动中按下工具栏上的向上按钮时,它将重新创建SecondActivity
,而不是返回到MainActivity
如果我使用后退按钮而不是向上按钮,那么它工作正常
可能存在什么问题以及如何解决?
我按下向上按钮,它只是破坏了第二个活动,并再次启动它
1条答案
按热度按时间e0bqpujr1#
您可以尝试以下操作