Reuse ViewGroup



我使用这种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>

我必须在我的片段中使用两个这样的布局,但有不同的图标和标题。有没有一些方法可以在没有复制/粘贴和RecyclerView的情况下实现它?

有几种方法可以处理它。

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>

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.只需复制粘贴即可:(

正如我所看到的,图标和标题是静态的,只有数据内容会发生变化,所以不值得重复使用这样一个简单的布局

最新更新