简体   繁体   English

在片段Android上按下后退按钮?

[英]Back button pressed on fragment android?

In my application i have 4 fragments like the follow [A] [A-sub] [B] [B-sub] when the user press back button from [A] or [B] it should exit the app suppose the user press back button from [A-sub] or [B-sub] it should redirect the app to [A] or [B] 在我的应用程序中,我有4个片段,例如:[A] [A-sub] [B] [B-sub],当用户从[A]或[B]中按返回按钮时,假设用户按回去,它将退出该应用程序[A-sub]或[B-sub]中的按钮,则应将应用重定向到[A]或[B]

I hope you got my problem 我希望你能解决我的问题

i have tried the follow in my main fragment activity but i know its only the solution for exit the app 我在我的主要片段活动中尝试了以下操作,但我知道这是退出应用程序的唯一解决方案

private boolean _doubleBackToExitPressedOnce    = false;

@Override
public void onBackPressed() {

System.out.println("onBackPressed--");
if (_doubleBackToExitPressedOnce) {
    super.onBackPressed();
    return;
}
this._doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

        _doubleBackToExitPressedOnce = false;
    }
}, 2000);
}

Do something like this, override onBackpessed() 做这样的事情,重写onBackpessed()

@Override
    public void onBackPressed()
    {
        if (page == SUB_FRG) 
            super.onBackPressed();//Normal Back
        else 
        //Finish activity holding fragment
    }

when u are replacing fragment to subfragment use addToBackStack(null) like following 当您将片段替换为子片段时,使用addToBackStack(null)如下所示

FragmentManager myProfilefragmentManager =  getSupportFragmentManager();
    FragmentTransaction myProfilefragmentTransaction = myProfilefragmentManager.beginTransaction();
    myProfilefragmentTransaction.replace(R.id.article_fragment, myProfileFragment).addToBackStack(null).commit();

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

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