I have 5 fragments and every fragment has three dots in top right corner which allows user to go to another child fragment. When user enter that fragment I want to allow them to go back to fragment they were before using back button arrow in right corner. I know if I had activities instead of fragments I could just do it in Android Manifest. I don't know if it is possible to call onClick() method on back arrow button because I created it through code so it does not have an id to select it.
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
To enable access to the home/up button from fragment you need to override and check item ID of android.R.id.home
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Do whatever you want here on home/up button click
// Replacing a fragment
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.addToBackStack("xyz");
fragmentTransaction.hide(MyCurrentFragment.this);
fragmentTransaction.add(android.R.id.content, fragment1);
fragmentTransaction.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
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.