2015-02-10 191 views
1

我想重複使用現有的佈局,而不是創建/編寫新的xml。目前,我喜歡這個。以編程方式膨脹以獲得android佈局

enter image description here

我想有這樣的程序,而不是書面的XML(可能是我想將它寫活動)。

enter image description here

我可以知道該怎麼辦?另外,另一個問題是,如果我這樣重複使用,「id」將是相同的。如果是這樣,我如何設置文本?

enter image description here

回答

2

添加的LinearLayout你的佈局,然後充氣,代碼多次header_description佈局,並把它添加到的LinearLayout。

更改佈局與此類似:

<include layout="@layout/header_list_image"/> 

<LinearLayout 
    android:layout_id="@+id/description_layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_contents" 
    android:orientation="vertical" > 

<include layout="@layout/header_url"/> 
<include layout="@layout/row_listing_like_comment_share"/> 
<include layout="@layout/header_comment_separator"/> 

在代碼中,使用id找到的LinearLayout,以及膨脹的描述佈局一個在時間和您的onCreate將它們添加()函數:

LinearLayout layout = (LinearLayout)findViewById(R.id.description_layout); 
LayoutInflater inflater = getLayoutInflater(); 

// add description layouts: 
for(int i = 0; i < count; i++) 
{ 
    // inflate the header description layout and add it to the linear layout: 
    View descriptionLayout = inflater.inflate(R.layout.header_description, null, false); 
    layout.addView(descriptionLayout); 

    // you can set text here too: 
    TextView textView = descriptionLayout.findViewById(R.id.text_view); 
    textView.setText("some text"); 
} 

此外,另一個問題是,如果我再利用這樣的,「ID」將是相同的。如果是這樣,我如何設置文本?

呼叫findViewById()上膨脹佈局e.g:

descriptionLayout.findViewById(R.id.text_view); 

不喜歡這樣的:

findViewById(R.id.text_view);