将多个视图添加到其他

时间:2015-05-02 21:05:35

标签: android android-layout

我的活动:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/city_detail_activity"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

我的布局xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shopping_movies"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/shopping_name"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </TextView>

    <TableLayout
        android:id="@+id/movies"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </TableLayout>
</LinearLayout>

我想要做的是创建我的布局的多个实例,并在我的活动中逐个添加。

我的活动代码是这样的:

for (int i =0; i < shoppings.size(); i++)
{
    LinearLayout shopping_movies = (LinearLayout)LayoutInflater.from(CityActivity.this).inflate(R.layout.shopping_movies, null);
    TextView shopping_name = (TextView) shopping_movies.findViewById(R.id.shopping_name);
    shopping_name.setText(shopp.name);

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayoutt.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

    addContentView(shopping_movies, params);
}

问题是每个布局都添加在位置0。一个在前面,而不是在下面。我刚试过addRule(LinearLayout.BELOW, lastId)但是没有用。我该怎么办?

2 个答案:

答案 0 :(得分:1)

使用LinearLayout代替android:orientation="vertical"代替RelativeLayout作为您观看的容器,因为orientationRelativeLayout中没有任何效果。

答案 1 :(得分:0)

我解决了在我的活动中添加空LinearLayout的问题。

MyActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/city_detail_activity"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

和我的java代码:

for (int i =0; i < shoppings.size(); i++)
{
    LinearLayout shopping_movies = (LinearLayout)LayoutInflater.from(CityDetailActivity.this).inflate(R.layout.shopping_movies, null);
    ((TextView) shopping_movies.findViewById(R.id.shopping_name)).setText(shopp.name);

    LinearLayout shoppingsViewGroup = (LinearLayout)findViewById(R.id.shoppings);

    shoppingsViewGroup.addView(shopping_movies);
}