包含布局的子元素的设置属性

问题描述 投票:40回答:3

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

<?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):

<?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”,但我不想让TextView包含自定义文本,而不是5次看到“ hello world”。

通过在include元素上设置一些属性以覆盖子TextView的文本,有什么方法可以做到?什么是实现这一目标的最佳方法?

android android-layout android-widget
3个回答
16
投票

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

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

<?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
}

7
投票

如果启用数据绑定,则可能:

reuse_layout.xml中>

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
       <variable name="text" type="String"/>
    </data>
    <LinearLayout 
        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="@{text}" />

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

    </LinearLayout>
</layout>

当您调用reuse_layout.xml

时,只需添加app:text属性
<layout="@layout/reuse_layout" app:text="some tex" />

© www.soinside.com 2019 - 2024. All rights reserved.