与具有相同ID
问题描述:
两个视图恢复片段我有一个复杂的布局来实现。 它有19个部分可以显示或不基于用户以前输入的大量参数。 为了简化代码并且不显示未使用的部分,布局是动态创建的。与具有相同ID
一切都是片段内。 片段有一个用作容器的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"/>
部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"/>
片段代码
@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);
// ...
}
适配器代码(两个同样的想法)
public Section2Adapter(LayoutInflater inflater, ViewGroup root) {
View view = LayoutInflater.from(context).inflate(R.layout.section_layout, root, false);
initView(view);
root.addView(view);
}
答
你需要什么要做的,就是告诉Android你自己在SparseArray
中哪个键保存的状态,其中EditText
。基本上,你需要得到这样的:
,通过它您实现这一目标是在this amazing article很好的解释,由帕夏杜德卡的机制。 (学分他漂亮的图像,也可以)
只要搜索“查看ID应该是唯一”的文章中,你将有你的答案。
您的特定情况的解决方案的要点是下列之一:
- ,那么可以继承
LinearLayout
S.T.你的CustomLinearLayout
会知道该小组属于何时其状态。这样,您可以保存所有子状态的部分专用只为那款SparseArray
内,并添加专用SparseArray
到全球SparseArray
(就像图像中) - 你也可以继承
EditText
,S.T.您的CustomEditText
知道它属于哪个部分,并且会将其状态保存在SparseArray
的自定义密钥中 - 例如,section_text_Section1
为第一部分,section_text_Section2
对于第二个
就个人而言,我更喜欢第一个版本,因为它会工作,即使你以后添加更多人观看您的部分。第二种方法不能处理更多的视图,因为在第二种情况下,智能状态保存不是父对象,而是视图本身。
希望这会有所帮助。
Wahoo!令人惊叹的答案! Thx非常,因为我不知道这一点。这正是我所期待的。 – Eselfar