gpt4 book ai didi

java - 在 Bundle 测试中设置 EditText 不起作用

转载 作者:行者123 更新时间:2023-12-01 20:17:27 25 4
gpt4 key购买 nike

您好,我正在练习 Bundle savingInstanceState 在 Activity 创建和恢复中的工作原理。我已经尝试过:

private EditText mTextBox;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextBox = (EditText) findViewById(R.id.etName);
mTextBox.setText("hello");
if(savedInstanceState != null){
Toast.makeText(this, savedInstanceState.getString("name"),
Toast.LENGTH_SHORT).show();
mTextBox.setText(savedInstanceState.geteString("name"));
}
}

@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("name", "Joe");
super.onSaveInstanceState(outState);
}

首先 onCreate() 显然这会将 EditText 字段设置为“hello”,因为 savedInstanceState 为 null if block 将不会被执行。当我更改方向时,Activity 会执行所有回调并在 if block 中烘烤字符串,但是,它不会设置 mTextBox传入的 Bundle 值。EditText 仍设置为 hello 而不是 Joe,但是, if block 中的 >Toast 显示 Joe

谁能指出为什么这没有达到我的预期?

谢谢

最佳答案

发生这种情况是由于 TextView.getFreezesText ,这将:

Return whether this text view is including its entire text contents in frozen icicles. For EditText it always returns true.

还有来自 TextView.setFreezesText 的更多信息:

Control whether this text view saves its entire text contents when freezing to an icicle, in addition to dynamic state such as cursor position. By default this is false, not saving the text. Set to true if the text in the text view is not being saved somewhere else in persistent storage (such as in a content provider) so that if the view is later thawed the user will not lose their data. For EditText it is always enabled, regardless of the value of the attribute.

icicles 指的是 savedInstanceState,这正是它过去的名称。

如果您想自己保存和恢复文本,您可以创建自定义 EditText 并覆盖 getFreezesText,例如:

public class NonFreezingEditText extends AppCompatEditText {

public NonFreezingEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public boolean getFreezesText() {
return false;
}

}

您还可以使用 View.post :

mTextBox.post(() -> mTextBox.setText(savedInstanceState.getString("name")));

Activity.onRestoreInstanceState

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTextBox.setText(savedInstanceState.getString("name"));
}

关于java - 在 Bundle 测试中设置 EditText 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45497505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com