2014-03-31 22 views
0

正在开发使用navigationDrawerAndroid应用程序。我希望抽屉在五秒钟后自行关闭它,这是它的作用。问题是navigationDrawer关闭后thread正在运行。所以如果我在2秒钟后手动关闭navigationDrawer,然后重新打开它,约3秒后它会自动关闭。关闭导航带处理程序计时器的抽纸机

我能做些什么来解决这个问题?我一直试图杀死处理程序,但无法使其正常工作。

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

     public void onDrawerClosed(View view) { 
      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(); 

     } 
    }; 

回答

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); 

    } 
}; 
+0

没有工作,线程仍在运行并关闭抽屉。 – Stains

+0

嗯,也许尝试使用静态布尔值 – kstachniuk

+0

与以前一样的问题。 – Stains

0

您可以拨打handler.removeCallbacks(Runnable)摆脱挂起(不是喷执行)可运行的。但要做到这一点,你必须修改你的代码。使处理器全球,使全球的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 
} 

在您身边的回调,从抽屉中取出的可运行:

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(); 
} 
+0

我仍然害怕同样的问题。 – Stains

+0

removeCallbacks()不杀死已经运行的线程,它只是清除队列。任何其他选项? – Stains

+0

删除布尔型drawerOpened。 –