Denver Shenal
Denver Shenal

Reputation: 419

Handle back button actions inside android fragments

i needed to override the default back button behavior so that i could go to the previous fragment instead of closing the entire application.

Below is the implementation of this function

class DataFragment : Fragment() {

private lateinit var fragment: Fragment
private lateinit var fm: FragmentManager
private lateinit var transaction: FragmentTransaction 

override fun onCreateView(
    inflater: LayoutInflater,
    @Nullable container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
            fragment = PreviousFragment()
            fm = parentFragmentManager
            transaction = fm.beginTransaction()
            transaction.replace(R.id.contentFragment, fragment)
            transaction.commit()
        }
    })
return binding.rootView
 }
}

Upvotes: 0

Views: 1117

Answers (2)

cactustictacs
cactustictacs

Reputation: 19534

When you perform a FragmentTransaction, you can call addToBackStack to put that transaction on the back stack. When the user hits the back button, the last transaction on the stack is popped off, and all the changes in that transaction are reverted.

So if a transaction replaces Fragment A with Fragment B, and also adds Fragment C, popping that transaction with the back button (or popBackStack()) will undo that and restore it back to how it was, with just Fragment A. So you can build up specific history states the user can step back through (like a web browser) and control exactly what the back button does.

You can also provide a label with addToBackStack (use null if you don't care), and then call popBackStack with that label to jump back to that transaction (or the one before it) in one go. So you can create a workflow where the user can back through steps one at a time, or hit a button that jumps right back to a specific step you've marked, like the start of some task, or an overview, etc

Upvotes: 1

Jayaraju Medisetti
Jayaraju Medisetti

Reputation: 52

public interface OnBackPressedListener {
    /**
     * register and implement OnBackPressedListener in fragment 
     * @update status onBackPressed() from Activity to current fragment to handle super.onBackPressed(); or to continue next process
     */
   void onBackPressed();
}

Upvotes: 1

Related Questions