2013-03-20 75 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

相关问题