如何一起使用FLAG_ACTIVITY_REORDER_TO_FRONT和onBackPressed()
-
13-12-2019 - |
题
我正在创建一个向导式的应用程序,在那里我需要保持活动A和B之间的用户数据活跃。A有下一个软按钮,B有一个后退软按钮。
使用时 FLAG_ACTIVITY_REORDER_TO_FRONT
我可以在使用软按钮时保持用户数据活着,因为每个活动都被重用。
但是,当用户从B按下后退硬按钮时,B死亡,因为硬按钮隐式使用finish()。
然后,我尝试复盖 onBackPressed
在B中,添加与我的后退软按钮相同的行为,认为后退硬按钮的行为与前一个按钮完全相同(而不是完成B)。
现在,用硬键从B回到A,一切都很好。在焦点在A的这一点上,当用户再次按下后退硬按钮时,预期的行为是应用程序离开。
问题是预期的行为不会发生,因为B仍然活着;这样就复盖了 onBackPressed
在B仍然在听,而其他一些行为ocurr代替。
我怎样才能用超负荷听完呢? onBackPressed
在B中,以便当焦点在a中时应用程序离开?
先谢谢你。
解决方案 2
好吧,我可以用一个自然的Android解决方案解决我的问题:
按照Krylez提示,我已经停止使用FLAG_ACTIVITY_REORDER_TO_FRONT,所以我不再与硬按钮冲突,现在我正在回收启动我的向导的意图。
在A中,我有一个非常常见的方法,当用户按下继续软按钮转到B时调用。活动A只是信息性的,所以它不需要在转到B时将Intent的额外内容与用户的数据放在一起,就像这样:
/** Called when the user presses the Continue button*/
public void continueButtonOnClick(View view) {
Intent intent = this.getIntent();
intent.setClass(this, StepOneRegisterWizardActivity.class);
startActivity(intent);
}
当活动B启动时,它总是必须寻找意图的额外内容中是否有用户的数据,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_one_register_wizard);
// Get the components of the content layout
usernameEditText = (EditText)findViewById(R.id.usernameEditText);
passwordEditText = (EditText)findViewById(R.id.passwordEditText);
getIntentExtras();
}
private void getIntentExtras() {
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
usernameEditText.setText(bundle.getCharSequence("usernameEditText"));
passwordEditText.setText(bundle.getCharSequence("passwordEditText"));
}
}
现在,也许从B,用户按下任何可用的后退按钮(软或硬)回到A。在这种情况下,我们需要将用户的数据放在Intent的extras中,如下所示:
/** Called when the user presses the Back soft button*/
public void backButtonOnClick(View view) {
onBackPressed();
}
@Override
/** Called when the user presses the Back hard button*/
public void onBackPressed() {
finish();
Intent intent = this.getIntent();
intent.setClass(this, StepZeroRegisterWizardActivity.class);
intent.putExtra("usernameEditText", usernameEditText.getText());
intent.putExtra("passwordEditText", passwordEditText.getText());
startActivity(intent);
}
最后,当用户再次按下继续软按钮时,新的活动B将具有用户每次输入的数据。
我希望它能帮助别人。