Android复合自定义视图恢复保存状态

joh*_*lib 5 android android-custom-view android-fragments

我创建了包含TextViewEditText调用的复合自定义视图LabledEditText,因为我将在一个片段中有很多 EditText 字段。

我创建了一个包含以下内容的 XML 文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayoutLabeledEditText"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/label_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/label"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/value_editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:freezesText="true"
        android:saveEnabled="true"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在 View 类中如下

public class LabeledEditText extends LinearLayout {
    private EditText editText;
    private TextView label;

    public LabeledEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context,R.layout.labeled_edit_text, this);
        label = (TextView) this.findViewById(R.id.label_textView);
        label.setText("some label");
        editText = (EditText) this.findViewById(R.id.value_editText);
    }

    protected void onRestoreInstanceState(Parcelable state) {
        String id= this.getId()+" ";
        if (state instanceof Bundle) // implicit null check
        {
            Bundle bundle = (Bundle) state;
            state = bundle.getParcelable(id+"super");
            super.onRestoreInstanceState(state);
            editText.setText(bundle.getString(id+"editText"));
        }
    }

    protected Parcelable onSaveInstanceState() {
        String id= this.getId()+" ";
        Bundle bundle = new Bundle();
        bundle.putParcelable(id+"super",super.onSaveInstanceState());
        bundle.putString(id+"editText",editText.getText().toString());
        return bundle;
    }   
}
Run Code Online (Sandbox Code Playgroud)

然后我在代表 3 个步骤的 3 个片段中使用它。当我在第一个步骤/片段中插入值时

访问第一步后的第一次

然后切换到其他片段并再次返回到 1 step/fragment 我发现以下内容

第二次访问第一步

是什么导致了这个问题?

我已经调试它至少 5 天了,记住每个自定义视图在片段布局中使用时都有不同的 id。

我还尝试在保存状态时将自定义视图的 id 添加为键的一部分,但this.getId()+"editText"仍然存在同样的问题。

编辑api < 17 的genrateViewId

修改后的代码

import java.util.concurrent.atomic.AtomicInteger;

public class LabeledEditText extends LinearLayout {
    private EditText editText;
    private TextView label;

    public LabeledEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context,R.layout.labeled_edit_text, this);
        label = (TextView) this.findViewById(R.id.label_textView);
        editText = (EditText) this.findViewById(R.id.value_editText);
        editText.setId(generateViewId());
        applyAttr(context,attrs);
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        //adding the id of the parent view as part of the key so that
        //editText state won't get overwritten by other editText 
        //holding the same id
        bundle.putParcelable("super",super.onSaveInstanceState());
        bundle.putString("editText",editText.getText().toString());
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) // implicit null check
        {
            Bundle bundle = (Bundle) state;
            state = bundle.getParcelable("super");
            super.onRestoreInstanceState(state);
            editText.setText(bundle.getString("editText"));
        }
    }

    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    public static int generateViewId() {
        for (;;) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

lio*_*ibe 8

你的问题是你有多个 ViewGroups (LinearLayout),孩子们有相同的 id。因此,在保存状态时,所有这些都以相同的状态保存,最后一个将全部覆盖。
为了解决这个问题,当你膨胀时,你必须给每个视图一个独特的 Id。在 v17 及更高版本中,您可以使用View.generateViewId();,在旧版本中,您必须在 ids 文件中手动创建静态 ID。
你的代码应该是这样的;

public LabeledEditText(Context context, AttributeSet attrs) { 
    super(context, attrs); inflate(context,R.layout.labeled_edit_text, this); 
    label = (TextView) this.findViewById(R.id.label_textView); label.setText("some label"); 
    editText = (EditText) this.findViewById(R.id.value_editText); 
    label.setId(View.generateViewId());
    editText.setId(View.generateViewId());
}
Run Code Online (Sandbox Code Playgroud)

在任何情况下,最好使用静态 ID,因为以后引用它们会更容易。您甚至可能不再需要覆盖 onSave 和 onRestore,尤其是当您使用静态 ID 时。