2012-02-21 30 views
4

如果我有一個佈局文件=>res/layout/item.xml<include>標籤override屬性

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

正如你見上面,我使用<include>標籤來包含相同的佈局。但是,如何覆蓋包含的item.xml中的「name」和「age」文本值main.xml對於每個包含的項目?

+0

你就錯了。只有當您計劃在同一應用的其他活動中重複使用「item」佈局時,才使用「include」標籤。 – Luksprog 2012-02-21 13:40:39

+0

這個http://stackoverflow.com/questions/2631614/does-android-xml-layouts-include-tag-really-work和這個http://stackoverflow.com/questions/4801710/how-to-set-attributes -inside-android-layout-that-is-included-in-another-layout即你只能覆蓋layout_ *屬性 – 2012-02-21 13:40:47

+3

你的意思是,即使所有的佈局對於「學生」,「老師」和「其他「項目,我仍然不能使用?但有沒有辦法避免重複創建相同的佈局代碼只有文本值不同? – 2012-02-21 13:46:34

回答

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); 
+0

這似乎是它會做的伎倆。爲什麼它低調? - 雖然這不適用於首選項佈局,因爲它們會自動存儲具有給定鍵的pref數據(它不會區分包含的不同實例)。 – Moberg 2013-08-16 07:22:39

-1

更改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");