I have a fragment:
public class MyFragment extends Fragment{
...
@Override
public View onCreateView(...){...}
...
}
I instantiate it:
MyFragment myFragment = new MyFragment();
I use the above fragment to replace the current fragment:
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// replace fragment
fragmentTransaction.replace(R.id.fragment_placeholder, myFragment, "myTag");
// NOTE: I did not add to back stack
Now, myFragment
is showing on the screen. NOTE: I did not add myFragment
to back stack.
My two questions:
1. If now, I press mobile phone back button, which fragment's life cycle callback will be invoked??
2. How can I customize the back button click listener in MyFragment
class? (please do not suggest me to do myFragment.getView().setOnclickListener
, but do it in MyFragment
class)
androidx.activity 1.0.0-alpha01 is released and introduces
ComponentActivity
, a new base class of the existingFragmentActivity
andAppCompatActivity
.You can now register an
OnBackPressedCallback
viaaddOnBackPressedCallback
to receiveonBackPressed
() callbacks without needing to override the method in your activity.Question 1: See http://developer.android.com/reference/android/app/Fragment.html#Lifecycle:
Question 2: If you must know that it was the back button specifically that is triggering the callbacks, You can capture the back button press in your Fragment's Activity and use your own method to handle it: