在父视图中多次动态地包含XML相对布局

时间:2013-03-20 02:37:59

标签: java android xml android-layout

我有一个XML RelativeLayout片段,我希望在主视图中多次(从循环中)包含这些片段。问题似乎是 - 有没有办法避免对RatingBar的父级进行硬编码,因为每次我包含RelativeLayout片段时,我的元素都需要有不同的ID?

据我所知,推荐的方法是获取布局片段然后覆盖每个元素的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 个答案:

答案 0 :(得分: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);
相关问题