【发布时间】:2020-03-18 10:24:52
【问题描述】:
希望你们在这些艰难时期一切都好。
我有 2 个活动,A 和 B。
A 有一个按钮,可以让 Intent 从 A 转到 B。B 本身有一个 Dialog 窗口,其 cancel 按钮可以让 Intent 从 B 转到 A。
我想从 A 中保存一些数据(2 个 EditTexts 的内容),所以当我回到 A 时,我不必重新输入那些 EditTexts。
所以在查阅了文档和一些 StackOverflow 之后,我决定使用 onSavedInstance 方法,但我想知道意图转换是否会破坏 Activity 以及因此也破坏了 savedInstance...
这是我的简化代码 - 活动 A:
public class A extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (savedInstanceState != null) {
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = savedInstanceState.getString("firstPlayerName");
String secondPlayerName = savedInstanceState.getString("secondPlayerName");
firstPlayer.setText(firstPlayerName);
secondPlayer.setText(secondPlayerName);
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
EditText firstPlayer = findViewById(R.id.firstPlayerName);
EditText secondPlayer = findViewById(R.id.secondPlayerName);
String firstPlayerName = String.valueOf(firstPlayer.getText());
String secondPlayerName = String.valueOf(secondPlayer.getText());
savedInstanceState.putString("firstPlayerName", firstPlayerName);
savedInstanceState.putString("secondPlayerName", secondPlayerName);
}
}
当我调试它时,我注意到它通过 onSavedInstance 并保存了值,但是一旦在 onCreate 中,savedInstanceState 为空。
有什么建议吗?
在此先感谢并照顾好人们。
票价。
【问题讨论】:
标签: java android android-intent android-activity