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
}
}
CodePudding user response:
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 replace
s Fragment A with Fragment B, and also add
s 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
CodePudding user response:
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();
}
CodePudding user response:
The answer that helped me achieve this was given by tanvir993
with a few tweaks i was able to achieve the required functionality in Kotlin easily