12

我正在遵循单一活动方法。我有导航工具栏,每当我转到其他屏幕(片段)而不是汉堡包图标时,我都会有后退箭头。

我想要实现的是,使用按下工具栏后退箭头的动作弹出我当前的片段。

我试过了

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);
    }
});

但是没有接到电话,我通过在调试模式下运行应用程序进行了检查。

4

4 回答 4

20

Activity创建:

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)

和:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) {
        onBackPressed()
        return true
    }
    return true
}

然后在你的片段中:

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)
}
于 2020-05-22T05:53:02.683 回答
2

在父活动中添加此代码

添加 onCreate 方法

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

在父活动中也添加此方法

 @Override
public boolean onSupportNavigateUp() {
    return super.onSupportNavigateUp();
}
于 2019-10-23T06:46:48.547 回答
1

如果您custom toolbar在 xml 中使用,您可以考虑使用以下方法

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_chat)

    setSupportActionBar(activity_chat_toolbar)

       
   activity_chat_toolbar.setNavigationOnClickListener {
        onBackPressed() <-- custom toolbar's back press
    }

    val navHostFrag =
            supportFragmentManager.findFragmentById(R.id.chat_fragment_container_view) as NavHostFragment
    navController = navHostFrag.navController
    navController.setGraph(R.navigation.chat_nav_graph, intent.extras)

    setupActionBarWithNavController(navController)
}

// Function to check startDestination to finish() the parent activity
override fun onBackPressed() {
    if(navController.graph.startDestination == navController.currentDestination?.id) {
        finish()
    } else {
        super.onBackPressed()
    }
}

override fun onSupportNavigateUp(): Boolean {
   return navController.navigateUp() || super.onSupportNavigateUp()
}
于 2021-03-13T08:21:27.570 回答
-1
Toolbar toolbar = findviewbyid(R.id.toolbar);
toolbar.setnavigationonclicklistener(new view.onclicklistener(){
 code here  
});
setsupportactionbar(toolbar);
于 2019-10-23T06:54:28.430 回答