以编程方式将视图添加到 Parent LinearLayout 在旋转设备时复制最后一个条目

Programmatically Adding Views to Parent LinearLayout Duplicates Last Entry when Rotating Device

我只做了几个月的 android 编程,所以我可能会在这里做一些愚蠢的事情...

在我的 activity 中,我使用带有 LinearLayout 的布局文件,我以编程方式将 child 视图添加到 activity 的 OnCreate() 中。 child 视图有一个布局文件,它包含 3 个 EditText,我用保存在某处的数据填充它们。

当我导航到 activity 并首次调用 onCreate() 时,每个 child 视图都会被填充 how I would expect. However, if I rotate the display from portrait -> landscape or vice-versa, when the page refreshes, all child views have the content of the last child view。当我使用断点单步执行代码时,一切看起来都很好:parent LinearLayout 具有预期的 child 视图,并且 child 视图填充了预期的数据。所以,我不知道为什么所有 child 视图都有最后一个 child 的数据,以及为什么这只在旋转时发生。无论设备大小或方向如何,我在这里都使用相同的布局文件。

有什么想法吗?

edit_profile_activity.xml:

<android.support.design.widget.CoordinatorLayout
    ...>

    <android.support.design.widget.AppBarLayout
        ...>

        <android.support.v7.widget.Toolbar
            .../>

    </android.support.design.widget.AppBarLayout>

    <!-- The main content view -->
    <android.support.v4.widget.NestedScrollView
        ...>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <!-- Edit Allies -->
            <LinearLayout
                android:id="@+id/profile_edit_ally_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/left_margin"
                android:paddingRight="@dimen/right_margin"
                android:orientation="vertical">

                <!-- This content is added programmatically. -->

            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

edit_profile_activity_ally_list_item.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/profile_edit_ally_name_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint="Name"
        android:imeOptions="flagNoExtractUi"
        android:inputType="textNoSuggestions"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_init_mod_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Init Mod"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_caster_level_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Caster Level"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <ImageButton
        android:id="@+id/profile_edit_delete_ally_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/ic_delete"/>
</LinearLayout>

在我的 activity:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.edit_profile_activity);

    // ...

    mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);
    for (TreeMap.Entry<String, AllyDB_Data> entry : mProfileData.mAllies.entrySet())
    {
        addAllyRowToLayout(entry.getKey(),
            Integer.toString(entry.getValue().mCasterLevel),
            Integer.toString(entry.getValue().mInitMod));
    }

    // Make sure there's at least one "empty" ally set.
    if (mAllyLayout.getChildCount() <= 0)
    {
        addAllyRowToLayout(null, null, null);
    }

    // ...
}

// ...

private void addAllyRowToLayout(String name, String casterLevel, String initMod)
{
    // Inflate the Ally Row
    View ally_layout_row = getLayoutInflater().inflate(R.layout.edit_profile_activity_ally_list_item, null, false);

    // EditText Name
    EditText name_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_name_edit_text);
    name_edit_text.setTextSize(14.0f);
    name_edit_text.setTextColor(Color.DKGRAY);
    if (name != null)
    {
        if (name.isEmpty() == false)
        {
            name_edit_text.setText(name);
        }
    }
    name_edit_text.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            invalidateOptionsMenu();
        }

        @Override
        public void afterTextChanged(Editable s) {}
    });

    // EditText Init Mod
    EditText init_mod_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_init_mod_edit_text);
    init_mod_edit_text.setTextSize(14.0f);
    init_mod_edit_text.setTextColor(Color.DKGRAY);
    if (initMod != null)
    {
        if (initMod.isEmpty() == false)
        {
            init_mod_edit_text.setText(initMod);
        }
    }

    // EditText Caster Level
    EditText caster_level_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_caster_level_edit_text);
    caster_level_edit_text.setTextSize(14.0f);
    caster_level_edit_text.setTextColor(Color.DKGRAY);
    if (casterLevel != null)
    {
        if (casterLevel.isEmpty() == false)
        {
            caster_level_edit_text.setText(casterLevel);
        }
    }

    // ImageButton Delete Ally Button
    ImageButton delete_button = (ImageButton) ally_layout_row.findViewById(R.id.profile_edit_delete_ally_button);
    delete_button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            View parent_view = (View) v.getParent();
            if (parent_view != null)
            {
                mAllyLayout.removeView(parent_view);
            }
            if (mAllyLayout.getChildCount() == 0)
            {
                addAllyRowToLayout("", "", "");
            }
        }
    });

    // Add the Ally Row to the Ally Layout.
    mAllyLayout.addView(ally_layout_row);
}

编辑 1 activity 的 onCreate() 中有一个 if 语句,我在第一次 posted 时未能显示。 if (allyLayout.getChildCount() <= 0) ...

编辑 2 看着 this post 让我想到 onRestoreInstanceState(Bundle savedInstanceState) 中发生了什么。令我惊讶的是,覆盖它并使其为空,解决了我的问题。不知道是不是最正统的方案

这一行之后:

mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);

检查您的线性布局是否有一些视图。

   if (mAllyLayout.getChildCount()>0){
    //add your views

    }

更新 如果您不想在轮换后处理数据,请将此添加到您的清单中:

<activity
            android:name="Your activity"
            android:configChanges="orientation|keyboardHidden|screenSize"/>