Setting attribute of child element of included layout

后端 未结 3 1661
情书的邮戳
情书的邮戳 2021-02-03 18:46

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




        
相关标签:
3条回答
  • 2021-02-03 18:58

    It is possible if you enable data binding:

    In 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>
    

    when you call the reuse_layout.xml just add app:text attribute with it

    <layout="@layout/reuse_layout" app:text="some tex" />
    
    0 讨论(0)
  • 2021-02-03 19:07

    https://developer.android.com/training/improving-layouts/reusing-layouts.html

    You can set the android:id property of each include. That gives the id to the root element of the layout being included.

    Get that view by id then find the subview you want to change the text on.

    0 讨论(0)
  • 2021-02-03 19:15

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

    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" />
    

    Then in your Activity:

    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
    }
    
    0 讨论(0)
提交回复
热议问题