【问题标题】:How to use onBackPressed method in Fragments [duplicate]如何在片段中使用onBackPressed方法[重复]
【发布时间】:2018-06-28 05:21:26
【问题描述】:

我在导航抽屉活动中有片段(A、B、C)和片段(A2、A3、B2、B3)分别到片段 A 和 B。 我需要它们像这样工作:1)A -> B -> C -> B. 当我按下后退按钮时,我需要返回 A。也就是说,片段 A 是主要的 2)A-> A2- > A3 当我按下后退按钮时,我需要返回 A2,然后是 A。我尝试使用 addToBackStack(),它对第二个示例有帮助,但对第一个示例没有帮助。所以,帮帮我,非常感谢))) (对不起,我看不懂英文)

【问题讨论】:

  • 你可以查看Link
  • 给交易一个标签。并弹出标签独家。

标签: android fragment onbackpressed


【解决方案1】:

步骤 1. 制作一个这样的界面

public interface HostInterface {
        void changeCurrentFragmentTo(int currentFragmentId, Bundle bundle);
    }

   implement it in your Main Activity.

第 2 步。在您的片段中

    private HostInterface hostInterface;

        @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                hostInterface = (HostInterface) context;
            }

        @Override
            public void onActivityCreated(@Nullable Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);

                if (getView() != null) {
                    getView().setFocusableInTouchMode(true);
                    getView().requestFocus();
                    getView().setOnKeyListener(new View.OnKeyListener() {
                        @Override
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                                if (keyCode == KeyEvent.KEYCODE_BACK) {
                                    **hostInterface.changeCurrentFragmentTo(yorfragment,null);**
                                    return true;
                                }
                            }
                            return false;
                        }
                    });
                }
            }

第 3 步。现在您收到了Activity 的回电。根据您的Requirement拨打New Fragment

【讨论】:

  • 我必须用replace方法调用片段还是添加?我必须添加addToBackStack(null)?
  • 谢谢,对我有帮助。我在activity中调用接口,写了几个“if”案例
  • 呜呜呜,它对我有用
【解决方案2】:

您可以使用 FragmentManager 直接处理要显示或隐藏的片段。

var newFragmentTag = typeof(NewFragment).Name;
var newFragment = FragmentManager.FindFragmentByTag(newFragmentTag);
if(newFragment != null)
{
    FragmentManager.BeginTransaction().Hide(currentFragment).Show(newFragment).Commit();
}
else
{
    // new Instance of newFragment and hide/show ...
}

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2013-08-13
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多