简体   繁体   中英

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. The FoodActivity has the back-button in the title bar. I'm using setDisplayHomeAsUpEnabled to put a back mark at icon in title bar.

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. The user returns to the 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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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