Sha*_*hal 11 android android-toolbar android-mvvm android-navigation-graph
I'm following single activity approach. I have navigation toolbar, whenever i go to other screens (fragments) instead of hamburger icon i will have back arrow.
What i want to achieve is, pop my current fragment using action on pressing toolbar back arrow.
I've tried
requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
NavHostFragment.findNavController(EventDetailsFragment.this)
.navigate(R.id.action_nav_event_details_to_nav_home);
}
});
Run Code Online (Sandbox Code Playgroud)
But not getting the call over there, i checked by running app in debug mode.
Had*_*adi 16
in Activity oncreate:
navController = findNavController(R.id.my_nav_host)
//my_nav_host defined in activity xml file as id of fragment or FragmentContainerView
val appBarConfiguration = AppBarConfiguration(navController.graph)
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
Run Code Online (Sandbox Code Playgroud)
and:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return true
}
Run Code Online (Sandbox Code Playgroud)
then in your fragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val callback: OnBackPressedCallback =
object : OnBackPressedCallback(true /* enabled by default */) {
override fun handleOnBackPressed() {
//do what you want here
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
Run Code Online (Sandbox Code Playgroud)
在父活动中添加此代码
在onCreate方法中添加
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Run Code Online (Sandbox Code Playgroud)
也在父活动中添加此方法
@Override
public boolean onSupportNavigateUp() {
return super.onSupportNavigateUp();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7780 次 |
| 最近记录: |