有人能解释一下为什么savedInstanceState中的值为空吗?
我有3个小部件,一个edittext,按钮和textview。这个人输入他们想要的东西。这个短语会在文本视图中弹出。我想在翻动电话时保留输入。我试图保存状态,但是当活动被重新创建时,我的祝酒词说它是空的:
public class MainActivity extends AppCompatActivity {
private EditText input;
private TextView output;
private Button button;
private String newString = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText)findViewById(R.id.input);
output = (TextView) findViewById(R.id.output);
button = (Button)findViewById(R.id.button);
if (savedInstanceState!=null){
Toast.makeText(this, "SAVED IS " + savedInstanceState.getString("example"), Toast.LENGTH_SHORT).show();
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newString = input.getText().toString();
output.setText(newString);
}
});
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("example",newString);
}}
最佳答案
您需要使用此函数onSaveInstanceState(Bundle outState)
,即不使用PersistableBundle outPersistentState
的函数
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("example",newString);
}
void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState)只有在清单内的活动标记中指定了属性
persistableMode
时,才会调用此函数您可以阅读更多about it here
关于android - savedInstanceState返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41511162/