Android 重用视图组

Android 重用视图组,android,android-layout,Android,Android Layout,我使用这种视图组: <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=

我使用这种视图组:

<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个这样的布局,但具有不同的图标和标题。是否有一些方法可以在不复制/粘贴和回收视图的情况下实现它?

有几种方法可以处理它

1.使用include标记。 1.1。将LinearLayout移动到单独的文件中

1.2使用包含标签添加布局两次,使用不同ID:

<LinearLayout ...>
    <include layout="@layout/your_layout" android:id="@+id/first" />
    <include layout="@layout/your_layout" android:id="@+id/second" />
</LinearLayout>
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.复制粘贴即可:)
正如我看到的,图标和标题是静态的,只有数据内容发生了变化,所以我认为重用这样一个简单的布局是不值得的。

我认为您应该将其设置为自定义视图。创建DataContentView扩展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);
    }
}