我正在开发一个使用navigationDrawer
的Android
应用程序。我希望抽屉在五秒钟后自行关闭,它确实如此。问题是thread
在navigationDrawer
关闭后正在运行。因此,如果我在 2 秒后手动关闭navigationDrawer
,然后重新打开它,它将在 ~3 秒后自行关闭它。
我该怎么做才能解决这个问题?Iv一直试图杀死处理程序,但无法使其工作。
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();
}
};
试试这个:
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);
}
};
你可以调用handler.removeCallbacks(Runnable)来摆脱挂起的(不是jet执行的)可运行量。但要做到这一点,你必须稍微修改一下你的代码。使处理程序全局化,并使全局可运行,如下所示:
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();
}