【问题标题】:<include> tag override attribute<include> 标签覆盖属性
【发布时间】:2012-03-11 19:42:16
【问题描述】:

如果我有一个布局文件 => res/layout/item.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="60dp"

>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="John"
        />

    <TextView  
        android:id="@+id/age"
        android:layout_width="fill_parent"
        android:layout_height="26dip" 
        android:text="29" />
</LinearLayout>

我还有另一个布局文件,其内容包括上述几个项目=> res/layout/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="60dp"
        android:orientation="vertical"        
    >

    <!--How can I override "name" and "age" attribute in the included item layout-->        

    <include android:id="@+id/student" layout="@layout/tem" />

    <include android:id="@+id/teacher" layout="@layout/item" />

    <include android:id="@+id/other" layout="@layout/item" />

</LinearLayout>

正如你在上面看到的,我使用&lt;include&gt; 标签来包含相同的布局。但是,如何从 ma​​in.xml 中为每个包含的项目覆盖包含的 item.xml 中的“name”和“age”文本值?

【问题讨论】:

  • 你做错了。仅当您计划在同一应用的其他活动中重用确切的 item 布局时,才使用 include 标签。
  • 这个stackoverflow.com/questions/2631614/… 和这个stackoverflow.com/questions/4801710/… 即你只能覆盖layout_* 属性
  • 你的意思是,即使“学生”、“教师”和“其他”项目的所有布局都相同,我仍然不能使用 ?但是有什么办法可以避免重复创建相同的布局代码,只有文本值不同??

标签: android android-layout android-intent android-widget


【解决方案1】:
I hope this will work.

View v=(View)findviewbyid(R.id.student);

Textview name=(TextView)v.findviewbyid(R.id.name);

Textview age=(TextView)v.findviewbyid(R.id.age);

【讨论】:

  • 这似乎可以解决问题。为什么它被否决? - 虽然,这不适用于首选项布局,因为它们会自动使用给定键存储首选项数据(它不会区分包含的不同实例)。
【解决方案2】:

将您的 item.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="60dp"

>

    <TextView
        android:tag="item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="John"
        />

    <TextView  
        android:tag="item_age"
        android:layout_width="fill_parent"
        android:layout_height="26dip" 
        android:text="29" />
</LinearLayout>

然后:

//find the container which hold student: 
     ViewGroup containerStudent = findViewById(R.id.student);
   //find the child:
     TextView student_name =(TextView)containerStudent.findViewWithTag("item_name"); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多