2012-02-21 8 views
4

私は=>res/layout/item.xml 1つのレイアウトファイルをお持ちの場合:<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>タグを使用して同じレイアウトを含める。しかし、「name」と「age」のテキスト値は、付属ののitem.xmlからmain.xmlに変更するにはどうすればよいですか?

+0

。同じappの他のアクティビティで正確な 'item'レイアウトを再利用する予定がある場合にのみ' include'タグを使います。 – Luksprog

+0

this http://stackoverflow.com/questions/2631614/does-android-xml-layouts-include-tag-really-work and this and this http://stackoverflow.com/questions/4801710/how-to-set-attributes -inside-android-layout-another-layoutに含まれている、つまりlayout_ *属性だけをオーバーライドすることができます –

+3

"student"、 "teacher"、および "other"のすべてのレイアウトが同じであっても"アイテム、まだ使用できません?しかし、テキスト値だけが異なる同じレイアウトコードを繰り返し作成することを避ける方法はありますか? –

答えて

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

これはトリックを行うように思える。なぜそれはdownvotedですか? - これは、指定されたキーで自動的にprefデータを格納するため、優先レイアウトには機能しません(インクルードの異なるインスタンスを区別しません)。 – Moberg

-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"); 
関連する問題