![](/img/trans.png)
[英]refreshing a RecyclerView from onRestoreInstanceState() doesn't work
[英]TextView.onRestoreInstanceState() doesn't work
我的应用程序需要能够动态创建TextViews
,因此,如果我的应用程序曾经使用过GC或切换了方向,则我需要能够恢复它们。 问题是我不知道如何还原TextViews
的状态。 与保存其状态TextView.onSaveInstanceState()
似乎就好了工作,但是当Parcelable
传递给onRestoreInstanceState()
没有任何反应,所得的看法是只是空白。 这是一个简短的示例,不起作用:
public class MainActivity extends AppCompatActivity {
TextView v;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
ViewGroup main = (ViewGroup) findViewById(R.id.main);
v = new TextView(this);
main.addView(v);
if (state == null) {
v.setText("A simple message.");
} else {
v.onRestoreInstanceState(state.getParcelable("message"));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("message", v.onSaveInstanceState());
}
}
我已经在调试器中检查了state.getParcelable("message")
的值,它肯定具有所需的信息。 onRestoreInstanceState()
只是没有使用它。 任何帮助将不胜感激。
编辑:我搞砸了调试器。 该信息实际上从未写入捆绑包。 TextView.onSaveInstanceState()
返回了一个空的Parcelable。 那是真正的问题。
我想到了。 问题出在TextView.onSaveInstanceState()
而不是TextView.onRestoreInstanceState()
。 仅当您通过先调用TextView.setFreezesText(true)
明确要求状态时, TextView.onSaveInstaceState()
才保存状态。 惊喜! 谢谢Google。 还要注意,onRestoreInstanceState()不会还原FreezesText属性。 哦,谷歌。 你真是个疯子。 我们将如何处理您?
您可以选择实现onRestoreInstanceState()
,而不是在onCreate()
期间恢复状态,系统在onStart()
方法之后调用该方法。 仅当存在要还原的保存状态时,系统才调用onRestoreInstanceState()
,因此您无需检查Bundle是否为空:
保存您的活动状态:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
恢复您的活动状态:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.