android studio addview通常会添加前两个视图,但随后会开始在随机位置添加它们

android studio addview通常会添加前两个视图,但随后会开始在随机位置添加它们,android,xml,android-studio,layout-inflater,Android,Xml,Android Studio,Layout Inflater,下面是我用来膨胀和添加视图的代码: public void onAddField(View v) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert inflater != null; View rowView = inflater.inflate(R.layout.more_rooms, null);

下面是我用来膨胀和添加视图的代码:

         public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    assert inflater != null;
    View rowView = inflater.inflate(R.layout.more_rooms, null);
    // Add the new row before the add field button.
    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

}
以下是我正在膨胀的布局:

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:id="@+id/editText2"
    android:layout_width="245dp"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_marginEnd="5dp"
    android:layout_marginTop="5dp"
    android:ems="10"
    android:hint="add another room"
    android:inputType="textPersonName"
    android:paddingStart="10dp"
    tools:layout_editor_absoluteX="152dp"
    tools:layout_editor_absoluteY="16dp" />

<ImageButton
    android:id="@+id/img_del"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_gravity="top"
    android:layout_marginEnd="5dp"
    android:layout_marginTop="5dp"
    android:background="@null"
    android:onClick="onDelete"
    app:srcCompat="@android:drawable/ic_delete" />
        </LinearLayout>

我这里的问题是,当我按add按钮时,它会正常地添加前两个视图,但当我第三次按它时,它会在旧的2个视图之间添加一个新视图,现在这不是一个问题,因为我可以处理它,但它仍然困扰着我,因此如何修复这种行为,我想让新视图总是在上面创建,而旧视图在下面创建

以下是父容器的代码:

        <LinearLayout
        android:id="@+id/ll_more"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="85dp"
        android:layout_marginTop="45dp"
        android:orientation="vertical">

根据,要将视图添加到LinearLayout的顶部,应将
0
作为要添加到addView(view childView,int index)中的子视图的索引传递

因此,使用:
parentLinearLayout.addView(rowView,0)


希望它能起作用

是否尝试添加不带索引的行视图?示例
parentLinearLayout.addView(rowView)
+Liem Vo在处理它一个小时后,我发现了错误,它是此行parentLinearLayout.addView(rowView,parentLinearLayout.getChildCount()-1);在我用常量替换了parentLinearLayout.getChildCount()-1之后,它工作得很好,我不知道为什么它要用getChildCount执行此操作,因为它返回的值与常量相同。但是ID应该是动态的,我修复了它只是必须替换parentLinearLayout.getChildCount()-1带有常量,并且每次添加视图时,它都会递增,可能是parentLinearLayout.getChildCount()-1有一个错误,因为它返回了与常量相同的值。此参数是要添加视图的索引,而不是ID。它指定了视图应添加到的位置。因此,如果添加了一个子项,并使用索引0添加了第二个子项,则第一个子项将移动到索引1(位于最近添加的子项下方)。检查您正在使用的常数。也许它的值是0?