Повторное использование ViewGroup - PullRequest
0 голосов
/ 05 мая 2020

Я использую такую ​​ViewGroup:

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:src="@drawable/icon1"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1"/>

    <TextView
        android:id="@+id/data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Я должен использовать 2 таких макета в моем фрагменте, но с другим значком и заголовком. Есть ли способ реализовать это без копирования / вставки и RecyclerView?

1 Ответ

0 голосов
/ 05 мая 2020

Есть несколько способов справиться с этим.

1. Используйте тег include.

1.1. Переместите LinearLayout в отдельный файл.

1.2 Добавьте макет с помощью тега include два раза с разными идентификаторами:

<LinearLayout ...>
    <include layout="@layout/your_layout" android:id="@+id/first" />
    <include layout="@layout/your_layout" android:id="@+id/second" />
</LinearLayout>

1.3 Программно установите содержимое:

View first = findViewById(R.id.first);
first.findViewById(R.id.date).setText("05/05/2020");
View second = findViewById(R.id.second);
second.findViewById(R.id.date).setText("04/04/2020");

2 . Реализовать настраиваемый вид.

Также есть два способа. Первый - раздуть макет внутри FrameLayout. Второй - расширить LinearLayout и программно добавить контент. Я покажу вам первый.

public class YourCustomView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        inflate(context, R.layout.your_custom_view_layout, this);
    }

    public MyView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyView(Context context) {
        this(context, null);
    }

    public void setContent(int iconRes, int titleRes, String data) {
        findViewById(R.id.icon).setDrawableRes(iconRes);
        findViewById(R.id.title).setDrawableRes(titleRes);
        findViewById(R.id.data).setText(data);
    }
}

3. Просто скопируйте и вставьте его :)

Как я вижу, значок и заголовок имеют статус c, и изменяется только содержимое данных, поэтому не стоит повторно использовать такой простой макет, IMO.

...