繁体   English   中英

以夸大的布局更新TextView

[英]Update TextView in inflated Layout

我有一个名为的模板布局文件

template_dashboard_item.xml

它的内容是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" style="@style/DashboardItemContainer">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" style="@style/DashboardItem">
    <TextView style="@style/DashboardItemText" android:text="Application for Jane Doe has been added" android:textColor="@color/black" />
    <TextView style="@style/DashboardItemText" android:text="Added today at ..." android:layout_marginTop="10dp" />                 
</LinearLayout>

我正在通过膨胀模板并将其插入到这样的视图中来使用此模板布局

LinearLayout item = (LinearLayout) getLayoutInflater().inflate(R.layout.template_dashboard_item, items, false);
items.addView(item);

这样,我要多次插入它。

我想知道,在我插入(addView)之前,如何更新那里的TextViews(text)?

换句话说,如何获取TextView的对象? (我猜findViewById在这种情况下不起作用)。

为什么不可以在XML的两个文本视图中添加ID并使用TextView text = item.findViewById(R.id.your_id);

您可以为TextView分配一个ID并使用item.findViewById进行检索,也可以使用ViewGroup.getChildAt(int index)

 for (int i = 0 i < item.getChildCount(); i++) {
         View view = item.getChildAt(i);
         if (view instanceof TextView) {

         }
  }

为什么不创建这样的自定义布局

public class CustomView extends RelativeLayout {

    private TextView header;
    private TextView description;



    public Card(Context context) {
        super(context);
        init();
    }

    public Card(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public Card(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.view_layout, this);
        this.header = (TextView) findViewById(R.id.header);
        this.description = (TextView) findViewById(R.id.description);
    }


    public void setHeader(String header) {
        this.header.setText(header);
    }


    public void setDescription(String description) {
        this.description.setText(description);
    }

}

并添加布局

LinearLayout items = (LinearLayout) getLayoutInflater().inflate(R.layout.template_dashboard_item, items, false);
CustomView item = new CustomView(this);
item.setHeader("xxx);
item.setDescription("yyy");
items.addView(item);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM