使用处理程序计时器关闭NavigationDrawer

时间:2014-03-31 08:34:52

标签: android counter navigation-drawer android-handler

开发使用Android的{​​{1}}应用程序。我希望抽屉在五秒钟后自动关闭,这样做。问题是navigationDrawerthread关闭后正在运行。因此,如果我在2秒后手动关闭navigationDrawer,然后重新打开它,它将在约3秒后自动关闭。

我该怎么做才能解决这个问题?我一直试图杀死处理程序,但无法让它工作。

navigationDrawer

2 个答案:

答案 0 :(得分:0)

试试这个:

private static int counterValue = 1;
private static int lastCounterValue;

public void counter(final int counter) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (lastCounterValue == counter)
                {
                  mDrawerLayout.closeDrawer(mDrawerList_Right);
                  mDrawerLayout.closeDrawer(mDrawerList_Left);
                }
            }
        }, 5000);
    }

    public void onDrawerClosed(View view) {
        getActionBar().setTitle(mTitle);
    counterValue++;
        // calling onPrepareOptionsMenu() to show action bar icons
        invalidateOptionsMenu();
    }

    public void onDrawerOpened(View drawerView) {
        getActionBar().setTitle(mDrawerTitle);
        // calling onPrepareOptionsMenu() to hide action bar icons
        invalidateOptionsMenu();
    lastCounterValue = counterValue;
        counter(counterValue);

    }
};

答案 1 :(得分:0)

你可以调用handler.removeCallbacks(Runnable)来摆脱待处理的(不是喷射执行的)runnables。但要做到这一点,你必须稍微修改你的代码。使Handler成为全局,并创建一个像这样的全局Runnable:

Handler handler = new Handler();

public Runnable r = new Runnable() {
    @Override
    public void run() {
      mDrawerLayout.closeDrawer(mDrawerList_Right);
      mDrawerLayout.closeDrawer(mDrawerList_Left);
    }
}

现在你可以用你的方法调用它们:

public void counter() {

    handler.postDelayed(r, 5000); // call the runnable
}

在你从抽屉关闭回调中删除runnable:

public void onDrawerClosed(View view) {

    handler.removeCallbacks(r);

    getActionBar().setTitle(mTitle);
    // calling onPrepareOptionsMenu() to show action bar icons
    invalidateOptionsMenu();
}

public void onDrawerOpened(View drawerView) {
    getActionBar().setTitle(mDrawerTitle);
    // calling onPrepareOptionsMenu() to hide action bar icons
    invalidateOptionsMenu();
    counter();
}