我为Android应用设计了一个操作栏。在此操作栏中,有一个按钮,用于启动用于配置应用程序行为的Dialog Activity。如果我足够快地双击此按钮,我可以命令对话活动在实际出现之前启动两次,然后它看起来重复并且在视觉上重叠,我不想要这个。我尝试创建某种锁定机制,但它无法正常工作,因为我的Dialog Activity仅在执行了我的Main Activity调用方法(onOptionsItemSelected)中的所有代码后才启动。有没有办法避免这种形式发生?
我的代码是:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//ensure only one element from the option menu is launched at once (if you double click fast you could launch two)
Log.e("test", "onOptionsItemSelected ");
if(optionItemAlreadySelected == false)
{
optionItemAlreadySelected = true;
int id = item.getItemId();
if (id == R.id.action_sound_mode) {
//item.setVisible(false);
Intent intent = new Intent(this, SoundConfigurationActivity.class);
startActivity(intent);
optionItemAlreadySelected = false; //this code is executed before the activity is started!!!
return true;
}
}
return super.onOptionsItemSelected(item);
}
有没有办法知道对话活动何时已经关闭,并锁定机会再次打开它。
答案 0 :(得分:1)
您可以使用布尔变量来跟踪Dialog
的状态。单击按钮时,您设置mDialogShown = true
以阻止任何其他显示对话框请求。
现在当用户按下Back按钮并关闭Dialog时,onActivityResult被调用。
此时您确定Dialog已关闭。
我假设你的代码在一个Activity中:
class MainActivity extend Activity {
static final int SHOW_DIALOG_REQUEST = 1; // The request code
static boolean mDialogShown = false; // True if dialog is currently shown
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_sound_mode) {
showDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showDialog() {
if (!mDialogShown) {
mDialogShown = true;
Intent intent = new Intent(this, SoundConfigurationActivity.class);
startActivityForResult(intent, SHOW_DIALOG_REQUEST);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == SHOW_DIALOG_REQUEST) {
mDialogShown = false;
}
}
}
文档
https://developer.android.com/training/basics/intents/result.html
https://developer.android.com/guide/topics/ui/dialogs.html#ActivityAsDialog