视图未使用自动生成的捆绑包信息。
搜索堆栈溢出未产生任何结果。视图不是自定义的,具有唯一的名称ID。不重复:
findViewById not working for an include?
FindViewById() not finding View
其他视图正在按预期运行。唯一没有添加的内容是包含项,这是我可以找到的唯一区别。
问题描述:视图被隐藏,活动被重新创建,视图被显示。
详细信息:我有一个Button,它使用默认的android:onClick
属性,该按钮调用一个方法。此方法正在按预期方式工作。然后,我“翻转” Android设备,方向发生变化,导致其调用onSaveInstanceState(Bundle b)
。捆绑了有关活动的信息,销毁并重新创建了活动,然后按预期将保存的捆绑发送到onCreate(Bundle b)
。
然后,根据Android活动,该捆绑包将还原视图状态。
除了单个视图
class ExampleActivity extends AppCompatActivity {
public void hide(View view){
view.setVisibility(View.GONE);
}
}
活动XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/linear_layout_style"
tools:context=".ExampleActivity">
<View style="@style/another_style" />
<include layout="@layout/included_xml" />
<View style="@style/another_style" />
</LinearLayout>
包含的XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/linear_layout_style">
<!-- This was supposed to stay hidden after pressed, but it restores in a VISIBLE state -->
<Button
style="@style/the_style"
android:id="@+id/an_unique_id"
android:onClick="hide"
android:text="EXAMPLE: Hide" />
<!-- This is supposed to always be visibile, and it does -->
<Button
style="@style/the_style"
android:onClick="doOtherStuff"
android:text="Example: Always Available">
<requestFocus />
</Button>
</LinearLayout>
答案 0 :(得分:0)
保存的实例不会保存所有内容。我查看了TextView
的来源(Button
进行了扩展,仅比TextView
小得多),它并没有保存可见性。实际上,它唯一保存的是文本和文本选择,只有在您调用setFreezesText(true)
时才保存。同样,View.onSaveInstanceState()
不执行任何操作(只是返回一个空的保存状态)。
因此,您需要自己手动保存和还原它们。我认为Android在这方面做得很差。文档说:
默认实现会处理每个实例的大多数UI 在每个视图中调用View.onSaveInstanceState()为您设置状态 具有ID的层次结构,并保存当前ID 焦点视图(所有视图均通过默认实现还原) onRestoreInstanceState(Bundle))。
在查看平台源代码之后,这肯定会引起误解。我的意思是,这是来自牛轧糖的View.onSaveInstanceState()
的实现:
protected Parcelable onSaveInstanceState() {
mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
if (mStartActivityRequestWho != null) {
BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
return state;
}
return BaseSavedState.EMPTY_STATE;
}
我倾向于不同意这是“大部分工作”。