简体   繁体   English

如何使用标题栏中的后退按钮关闭片段?

[英]How to use Back-Button in the title bar for closing the fragment?

I have the activity for example: FoodActivity in this activity I created the grid of the type of Food, I used the RecyclerView for this propose.我有一个活动,例如:FoodActivity 在这个活动中我创建了食物类型的网格,我使用 RecyclerView 来提出这个建议。 The FoodActivity has the back-button in the title bar. FoodActivity 在标题栏中有后退按钮。 I'm using setDisplayHomeAsUpEnabled to put a back mark at icon in title bar.我正在使用 setDisplayHomeAsUpEnabled 在标题栏中的图标处放置一个后退标记。

supportActionBar?.setDisplayHomeAsUpEnabled(true)

The issue: when user clicked on type of Food item the new fragment is opened.问题:当用户点击食物类型时,新片段被打开。 But when user now click the Back button he return not to the previews FoodActivity with the RecyclerView items grid.但是,当用户现在单击“后退”按钮时,他不会返回到带有 RecyclerView 项目网格的预览 FoodActivity。 The user returns to the MainActivity.用户返回到 MainActivity。 It's not usable.它不可用。 I need the Back button just close the fragment, and return to the prev activity not to to the "prev-prev".我需要后退按钮来关闭片段,然后返回到上一个活动而不是“上一个-上一个”。

I found this chunk of code:我找到了这段代码:

override fun onAttach(context: Context) {
super.onAttach(context)
val callback: OnBackPressedCallback = 
                   object : OnBackPressedCallback(true) 
    {
    override fun handleOnBackPressed() {
        // Leave empty do disable back press or 
        // write your code which you want
    }
  }
    requireActivity().onBackPressedDispatcher.addCallback(
    this,
    callback
  )
 }

And it can help but it does not work with the back-button in the title bar.它可以提供帮助,但不适用于标题栏中的后退按钮。 This code works only with the default back button of the device.此代码仅适用于设备的默认后退按钮。 Is there a way to solve my issue?有办法解决我的问题吗?

Add below code in the onCreate method of your fragment:在片段的onCreate方法中添加以下代码:

setHasOptionsMenu(true)

This method call will allow your fragment to populate the options menu including the back icon in the toolbar.此方法调用将允许您的片段填充选项菜单,包括工具栏中的后退图标。

Now you can override the onOptionsItemSelected method to perform actions whenever any of the buttons is pressed, in your case the top back arrow.现在您可以重写onOptionsItemSelected方法以在按下任何按钮时执行操作,在您的情况下是顶部后退箭头。

override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
        // top back arrow is mapped to android.R.id.home 
        android.R.id.home -> {
               //Close the fragment and navigate back to Recyclerview
           }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM