我使用这种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的情况下实现它吗?
发布于 2020-05-06 00:18:56
有几种方法可以处理它。
1.使用include标签。
1.1。将LinearLayout移动到单独的文件。
1.2使用include标签两次添加具有不同ids的布局:
<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.只需复制粘贴即可:)
在我看来,图标和标题都是静态的,只有数据内容会发生变化,所以重用这样一个简单的布局是不值得的。
https://stackoverflow.com/questions/61614883
复制相似问题