2013-03-20 78 views
0

我有一個XML RelativeLayout片段,我希望在我的主視圖中包含多次(從一個循環)。問題似乎是 - 有沒有辦法避免對RatingBar的父級進行硬編碼,因爲每次我包含RelativeLayout片段時,我的元素都需要不同的ID?動態在父視圖中多次包含XML相對佈局

據我所知,推薦的方法是獲取佈局片段,然後重寫每個元素的android:id爲唯一,然後爲具有相對定位的每個元素手動覆蓋android:layout_below。這看起來有點奇怪 - 有沒有辦法讓這些綁定自動完成?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dp" 
    android:id="@+id/relativeView"> 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="5dp" 
     android:text="Label" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <RatingBar 
     android:id="@+id/ratingBar1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/textView1" /> 

</RelativeLayout> 

回答

1

你只需要改變RelativeLayout 的ID喜歡

int BASEID=200; 

View v = mLayoutInflator.inflate(R.layout.myRelativeLayout, null); 

for (int i;i<10;i++){ 
    v.findViewById(R.id.relativeView).setId(i+BASEID); 
} 

mRootView.addView(v,...); 

那麼當你需要得到RatingBar爲假設你添加的第4 RelativeLayout你可以叫

RatingBar mRatingBar = (RatingBar)mRootView.findViewById(BASEID+3).findViewById(R.id.ratingBar1); 
+0

謝謝 - 我最終將字符串列表中的元素數量從列表中移除,因此我只是將每個元素上的標記設置爲字符串值,這很有效。儘管如此。 – Cyclic 2013-04-03 03:57:59

相關問題