如何确保 Activity 在多次按下按钮后只打开一次
How to ensure that an Activity is only opened one time after pressed multiple time on button
我有一个按钮可以打开 activity。但我注意到,当我在 activity 出现之前多次按下按钮时,它会打开 activity 两次。 (我在我的 XML 中使用 android:onclick)所以我把这段代码:
AppCompatImageButton natureButton;
public void onClickButton(View view){
natureButton = findViewById(view.getId());
natureButton.setEnabled(false);
Intent intent = new Intent(this, QuestionActivity.class);
startActivity(intent);
}
@Override
protected void onStop() {
super.onStop();
//Enabled the button after activity is no longer visible to the user
natureButton.setEnabled(true);
}
我调用了 onStop() 来启用按钮,因为当 activity 不再可见时会调用 onStop()。
所以我想知道是否有更好的方法来做到这一点。
与其在 onStop
中启用按钮,更好的方法是在 onResume
中启用它。
@Override
protected void onResume() {
super.onResume();
if(natureButton != null)
natureButton.setEnabled(true);
}
尝试添加:
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
我有一个按钮可以打开 activity。但我注意到,当我在 activity 出现之前多次按下按钮时,它会打开 activity 两次。 (我在我的 XML 中使用 android:onclick)所以我把这段代码:
AppCompatImageButton natureButton;
public void onClickButton(View view){
natureButton = findViewById(view.getId());
natureButton.setEnabled(false);
Intent intent = new Intent(this, QuestionActivity.class);
startActivity(intent);
}
@Override
protected void onStop() {
super.onStop();
//Enabled the button after activity is no longer visible to the user
natureButton.setEnabled(true);
}
我调用了 onStop() 来启用按钮,因为当 activity 不再可见时会调用 onStop()。 所以我想知道是否有更好的方法来做到这一点。
与其在 onStop
中启用按钮,更好的方法是在 onResume
中启用它。
@Override
protected void onResume() {
super.onResume();
if(natureButton != null)
natureButton.setEnabled(true);
}
尝试添加:
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)