Почему использование LayoutInflater отличается от xml?

Я создал этот макет

<LinearLayout
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="20dp"
    android:layout_weight=".7" >
    <RelativeLayout
        android:layout_width="70dp"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dip"
            android:layout_marginRight="10dip"
            android:layout_marginLeft="10dip"
            android:src="@mipmap/icon" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:src="@mipmap/delete_button" />
        <TextView
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:textColor="@android:color/white"
            android:singleLine="true"
            android:textSize="10sp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:layout_below="@id/icon"
            android:text="name"/>
    </RelativeLayout>
</LinearLayout>

Выход

введите здесь описание изображения

Когда я уверен, что отображение правильное, я отделяю элемент в другой XML-файл.

mainactivity.xml

<LinearLayout
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="20dp"
    android:layout_weight=".7" >
</LinearLayout>

элемент.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="70dp"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginLeft="10dip"
        android:src="@mipmap/icon" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:src="@mipmap/delete_button" />
    <TextView
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textColor="@android:color/white"
        android:singleLine="true"
        android:textSize="10sp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:layout_below="@id/icon"
        android:text="name"/>
</RelativeLayout>

А затем добавьте элемент в onCreate основной активности

LayoutInflater inflater=LayoutInflater.from(this);
View view=inflater.inflate(R.layout.item, null, true);
list.addView(view); //(R.id.list), LinearLayout list

Теперь выход

введите здесь описание изображения

И даже я добавляю много видов в этот linearlayout, но в макет можно добавить только один вид

LayoutInflater inflater=LayoutInflater.from(this);
View view=inflater.inflate(R.layout.item, null, true);
View view2=inflater.inflate(R.layout.other_item, null, true);
list.addView(view); //(R.id.list), LinearLayout list
list.addView(view2);

Как правильно добавить представление в макет?


person CL So    schedule 02.07.2015    source источник
comment
Я не уверен, но проверьте эту ссылку, возможно, вы получите помощь clcik здесь   -  person Pankaj    schedule 02.07.2015
comment
просто используйте: inflater.inflate(R.layout.item, list)   -  person pskink    schedule 02.07.2015


Ответы (1)


Попробуйте это вместо этого:

View view = inflater.inflate(R.layout.item, list, false);
list.addView(view); //(R.id.list), LinearLayout list

Объяснение:

Второй аргумент inflate() — предполагаемый родитель представления, которое нужно раздуть. Когда вы передаете null в качестве второго аргумента, расширенное представление не получает никакого LayoutParams, потому что inflate() не знает, каким в конечном итоге будет родитель, и, следовательно, не может создать соответствующий LayoutParams (почти каждый ViewGroup определяет свой собственный подкласс LayoutParams).

Когда вы вызываете addView(), LinearLayout проверяет, есть ли у потомка LayoutParams и относятся ли они к соответствующему типу. Если нет, он генерирует некоторый LayoutParams по умолчанию для установки добавляемого представления. Какое бы значение по умолчанию оно ни давало ребенку, оно вызывает неожиданное поведение.

Короче говоря, решение состоит в том, чтобы передать list вместо null при вызове inflate().

person Karakuri    schedule 02.07.2015