onBackPressed with Fragments Android

时间:2015-05-14 18:52:27

标签: java android android-fragments onbackpressed

我正在尝试在包含3个片段的活动上实现onBackPressed。我的问题是我在一段时间之后实现了“再次按下退出”但是当单击后退按钮两次时它返回到前一个片段,而不是退出。当调用该片段时(即如果我打开游戏并立即退出它就像一个魅力),就会发生这种情况。我在MainActivity上的onBackPressed方法看起来像这样;

@Override
public void onBackPressed() {

    if(getSupportFragmentManager().getBackStackEntryCount()!=0) {
        getSupportFragmentManager().popBackStack();
    }
    this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
    if(mBackPressed + TIME_INTERVAL > System.currentTimeMillis() && getSupportFragmentManager().getBackStackEntryCount()==0){
        super.onBackPressed();
        System.exit(0);
        this.finish();
    }
    else { Toast.makeText(getBaseContext(), "Press back once more to exit", Toast.LENGTH_SHORT).show(); }

    mBackPressed = System.currentTimeMillis();
}

我基本上想检查用户是否在mainActivity布局中,所以我可以使用popBackStack来逃避。任何解决方案都将受到赞赏,如果这还不够,我可以提供更多信息。

谢谢, Bektaş

3 个答案:

答案 0 :(得分:1)

如果你真的想退出,请完全忽略后台。使用此代码。

@Override
public void onBackPressed() {
    this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
    if(mBackPressed + TIME_INTERVAL > System.currentTimeMillis()){
        this.finish();
        return;
    }
    else { 
       Toast.makeText(getBaseContext(), "Press back once more to exit", Toast.LENGTH_SHORT).show(); 
    }
    mBackPressed = System.currentTimeMillis();
}

答案 1 :(得分:0)

我认为您可能会发现此链接很有用 http://developer.android.com/training/implementing-navigation/temporal.html

它说你可以使用这个paturn

添加对堆栈的引用
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
                           .add(detailFragment, "detail")
                       // Add this transaction to the back stack
                       .addToBackStack()
                       .commit();

答案 2 :(得分:-1)

@Override
public void onBackPressed() {
    int count = getSupportFragmentManager().getBackStackEntryCount();
    if (count == 0) {
        getSupportFragmentManager().popBackStack(getSupportFragmentManager().getBackStackEntryCount(), getSupportFragmentManager().POP_BACK_STACK_INCLUSIVE);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        (Main Activity Name).super.onBackPressed();
                    }
                }).create().show();
    } else {
        super.onBackPressed();


    }
}