如何在片段中处理BackPress?

时间:2017-08-28 11:53:44

标签: android android-fragments onbackpressed fragment-backstack

< p>我的应用程序中有多个片段,而doubleBackPress则退出。问题是,无论在活动中显示哪个片段,都要激活要退出的doubleBackPress。< / p> < p>这是我尝试过的。< / p> < p> MainActivity中的代码< / p> <预><代码> @覆盖 public void onBackPressed(){     DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);     if(drawer.isDrawerOpen(GravityCompat.START)){         drawer.closeDrawer(GravityCompat.START);     } else {         if(doubleBackToExitPressedOnce){             if(getFragmentManager()。getBackStackEntryCount()> 0){                 getFragmentManager()popBackStack();             } else {                 super.onBackPressed();             }             返回;         }         this.doubleBackToExitPressedOnce = true;         Toast.makeText(this,"再次按回退出",Toast.LENGTH_SHORT).show();         new Handler()。postDelayed(new Runnable(){             @覆盖             public void run(){                 doubleBackToExitPressedOnce = FALSE;             }         },2000);     } } < /代码>< /预> < p>这就是我发布片段的方式。< / p> < pre>< code> fragmentManager = getFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); CategoryFragment categoryFragment = new CategoryFragment(); fragmentTransaction.replace(R.id.container,categoryFragment); fragmentTransaction.addToBackStack(NULL); fragmentTransaction.commit(); < /代码>< /预>

2 个答案:

答案 0 :(得分:1)

您可以根据需要参考以下代码。如果您不使用v4支持片段,则必须使用getFragmentManager()而不是getSupportFragmentManager()来获取backstack计数。这里我使用布尔值来检查是否单击了后退,如果在2秒内没有再次单击它,它将再次变为假。

boolean doubleBackToExitPressedOnce = false;
    @Override
    public void onBackPressed() {
        //Checking for fragment count on backstack
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else if (!doubleBackToExitPressedOnce) {
            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        } else {
            super.onBackPressed();
            return;
        }
    }

我希望这对你有所帮助。

答案 1 :(得分:0)

你正在替换片段试试这个:

fragmentTransaction.add(R.id.container,categoryFragment);

而不是

fragmentTransaction.replace(R.id.container,categoryFragment);