首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重用ViewGroup

重用ViewGroup
EN

Stack Overflow用户
提问于 2020-05-05 21:57:31
回答 1查看 45关注 0票数 1

我使用这种ViewGroup:

代码语言:javascript
复制
<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的情况下实现它吗?

EN

回答 1

Stack Overflow用户

发布于 2020-05-06 00:18:56

有几种方法可以处理它。

1.使用include标签。

1.1。将LinearLayout移动到单独的文件。

1.2使用include标签两次添加具有不同ids的布局:

代码语言:javascript
复制
<LinearLayout ...>
    <include layout="@layout/your_layout" android:id="@+id/first" />
    <include layout="@layout/your_layout" android:id="@+id/second" />
</LinearLayout>

1.3以编程方式设置内容:

代码语言:javascript
复制
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并添加内容。我会给你看第一个。

代码语言:javascript
复制
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.只需复制粘贴即可:)

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61614883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档