包含布局的子元素的设置属性 [英] Setting attribute of child element of included layout

查看:56
本文介绍了包含布局的子元素的设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个main.xml文件,它描述了我的主要活动的布局:

I have a main.xml file describing the layout of my main activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include layout="@layout/mylayout" />
    <include layout="@layout/mylayout" />
    <include layout="@layout/mylayout" />
    <include layout="@layout/mylayout" />
    <include layout="@layout/mylayout" />
    <include layout="@layout/mylayout" />

</LinearLayout>

及其包含的布局xml文件(mylayout.xml):

and its included layout xml file (mylayout.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mylayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello world" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

我只想在主布局中包含5次"mylayout",但不是希望5次看到"hello world",而是希望TextView包含自定义文本.

I just want to include "mylayout" in my main layout 5 times, but instead of seeing "hello world" 5 times, I want the TextView to contain custom text.

是否可以通过在include元素上设置一些属性来覆盖子TextView的文本来实现此目的?达到此目的的最佳方法是什么?

Is there any way to do this by setting some attribute on the include element to override the child TextView's text? What would be the best approach to take to accomplish this?

推荐答案

否,除了使用<include>指令的布局参数外,没有其他方法可以将参数传递到所包含的布局.

No, there is no way to pass parameters to the included layout other than the layout params using the <include> directive.

您可以通过编程使布局膨胀并将其添加到视图中.在主布局中向容器添加ID:

You can inflate the layout programatically and add them to your view. Add an id to the container in your main layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" />

然后在您的活动中:

ViewGroup container = (ViewGroup)findViewById(R.id.container);
for (int i = 0; i < 6; i++) {
    View myLayout = getLayoutInflater.inflate(R.layout.mylayout, null);
    TextView tv = myLayout.findViewById(R.id.textView);
    tv.setText("my layout " + i);
    container.addView(myLayout); // you can pass extra layout params here too
}

这篇关于包含布局的子元素的设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆