繁体   English   中英

从片段返回到上一个主片段的按钮箭头

[英]Back Button Arrow from Fragment to previous home fragment

我有 5 个片段,每个片段在右上角都有三个点,允许用户将 go 指向另一个子片段。 当用户输入该片段时,我想让他们 go 回到片段,他们在使用右上角的后退按钮箭头之前。 我知道如果我有活动而不是片段,我可以在 Android 清单中进行。 我不知道是否可以在后退箭头按钮上调用 onClick() 方法,因为我是通过代码创建的,所以它没有 select 的 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;
}

要允许从片段访问主页/向上按钮,您需要覆盖并检查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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM