Ese*_*far 6 android android-fragments onsaveinstancestate
我有一个复杂的布局来实现.它有19个部分可以根据用户先前输入的大量参数显示或不显示.为了简化代码并且不显示未使用的部分,动态创建布局.
一切都在碎片里面.片段有一个用作容器的LinearLayout,当创建片段时,我生成所有必要的部分.
每个部分由其自己的本地适配器管理,该适配器负责扩展此部分的布局并将其添加到容器中.
一切都很好.问题是2个部分具有完全相同的结构,因此它们共享相同的xml布局.因此,两个部分的内部视图具有相同的ID.这不是问题,因为该部分在其适配器中本地管理.当我转到下一个片段然后再回到这个片段时,会出现问题.系统尝试恢复视图的先前状态,并且由于这两个部分具有相同的ID,因此在恢复第二部分时,其值也将设置为第一部分.
是否有任何解决方案来管理它或告诉片段不恢复其状态(因为无论如何都要手动重新加载).
这是当前结构的一个很好的例子:
片段xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Run Code Online (Sandbox Code Playgroud)
部分xml
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/section_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)
片段代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_layout, container, false);
if (<condition>)
createSection1(getContext(),view);
if (<condition>)
createSection2(getContext(),view);
return view;
}
private void createSection1(Context context, ViewGroup root){
Section1Adapter adapter = new Section1Adapter(context, root);
// ...
}
private void createSection2(Context context, ViewGroup root){
Section2Adapter adapter = new Section2Adapter(context, root);
// ...
}
Run Code Online (Sandbox Code Playgroud)
适配器代码(两者的想法相同)
public Section2Adapter(LayoutInflater inflater, ViewGroup root) {
View view = LayoutInflater.from(context).inflate(R.layout.section_layout, root, false);
initView(view);
root.addView(view);
}
Run Code Online (Sandbox Code Playgroud)
你需要做的是告诉Android自己在哪个键中SparseArray保存状态EditText.基本上,你需要达到这个目的:
Pasha Dudka 在这篇惊人的文章中很好地解释了实现这一目标的机制.(还有他的好照片,还)
只需在文章中搜索"查看ID应该是唯一的",您就会得到答案.
针对您的特定情况的解决方案的要点如下:
LinearLayout你的CustomLinearLayout遗嘱子类知道你所知道的一个子属于它的状态.这样,您可以将一个部分中的所有子状态保存到SparseArray专用于该部分,并将专用添加SparseArray到全局 SparseArray(就像在图像中一样)EditText,CustomEditText知道它属于哪个部分,并将其状态保存在自定义键中SparseArray- 例如section_text_Section1第一部分和section_text_Section2第二部分就个人而言,我更喜欢第一个版本,因为即使您稍后在章节中添加更多视图,它也会起作用.第二个不适用于更多的视图,因为在第二个不是父节点进行智能状态保存,而是视图本身.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |