我有 5 个 fragment ,每个 fragment 的右上角都有三个点,允许用户转到另一个子 fragment 。当用户输入该 fragment 时,我想让他们返回到使用右上角的后退按钮箭头之前的 fragment 。我知道如果我有 Activity 而不是 fragment ,我可以在 Android Manifest 中完成。我不知道是否可以在后退箭头按钮上调用 onClick() 方法,因为我是通过代码创建它的,所以它没有用于选择它的 ID。
@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;
}
最佳答案
要启用从 fragment 访问主页/向上按钮,您需要覆盖并检查 android.R.id.home
的项目 ID
@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);
}
关于java - 从 fragment 到上一个主页 fragment 的后退按钮箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61777751/