26
2017
09

android 连按两次Back键退出 (单Activity多Fragment,保留根Fragment)

代码

    protected boolean doubleBackToExitPressedOnce = false;

    protected void backStackAndDoubleBackExit() {
        int backStackEntryCount = 2;
        int delayMillis = 3 * 1000;

        if (getSupportFragmentManager().getBackStackEntryCount() > backStackEntryCount ) { 
            // super.onBackPressed();
            getSupportFragmentManager().popBackStackImmediate();
        } else if (getSupportFragmentManager().getBackStackEntryCount() == backStackEntryCount ) {

            if (doubleBackToExitPressedOnce) {
                finish();
            }
            doubleBackToExitPressedOnce = true;
            Snackbar.make(getRootView(), "please click back button again to exit",
                        Snackbar.LENGTH_SHORT).show();
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, delayMillis );
        }

    }

根据 getBackStackEntryCount(); 方法,判断Fragment返回栈,Fragment数量
使用 popBackStackImmediate() 方法,消除super关键字的限制
添加变量 backStackEntryCount, 存储根Fragment所占数量
Toast 更改为 Snackbar


使用

1 代码复制至BaseActivity
2 xxxActivity 继承BaseActivity
3 onbackPressed()方法调用backStackAndDoubleBackExit()方法


end

上一篇:Android系统中常用的Uri 下一篇:SSH框架整合的MAVEN项目之配置文件整合