【发布时间】:2012-03-29 16:36:23
【问题描述】:
我遇到了一个问题,我知道根本原因,但没有找到解决方法。如果在一个活动中多次使用自定义复合组件,则从视图中保存的值将相互覆盖。为了更容易解释,我做了以下示例。
新组件的 xml,只有一个 EditText 使它更短。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<EditText
android:id="@+id/custom_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
</EditText>
</merge>
实现新行为的类,仅扩展布局。
public class CustomView extends LinearLayout {
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_view, this, true);
}
}
以及使用其中 2 个的布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<test.customview.CustomView
android:id="@+id/customView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</test.customview.CustomView>
<test.customview.CustomView
android:id="@+id/customView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</test.customview.CustomView>
</LinearLayout>
当屏幕旋转时,第二个视图的值也恢复到第一个视图中。
深入研究框架的代码,我发现从 View 类中定义的 onSaveInstanceState 返回的 Parcelable 对象被放入带有关键对象 id 的 SparseArray 中。因为我多次包含CustomView,所以ID为“custom_text”的EditText也被多次添加。 id相同,保存的值会互相覆盖。
我正在寻找有关如何实际实施的任何建议。目前,我看不到任何更改这些标识符的方法。
【问题讨论】:
标签: android android-layout android-widget android-custom-view