动态地向ListView项添加视图不起作用

时间:2014-06-30 12:07:05

标签: android listview android-listview

我有ListView,它总是包含两个不同的子视图。

现在我想使用第一个(位置== 0)。它的膨胀视图包含ImageViewRelativeLayout(必须包含标记)。

在尝试向第一项RelativeLayout添加一些视图后,我看到它们已被添加但变得不可见。方法RelativeLayout.getChildCount()返回正确的值,但添加的标记不可见。

ListView适配器:

 @Override
public View getView(int position, View view, ViewGroup parent) {
    switch (position) {
        case 0:
            view = (RelativeLayout) LayoutInflater.from(act).inflate(R.layout.item_choose_color_picture, parent, false);
            ((ImageView) ((RelativeLayout) view).findViewById(R.id.item_choose_color_image)).setImageBitmap(bitmap);
            return view;
        case 1:
            view = (ImageView) LayoutInflater.from(act).inflate(R.layout.item_choose_color_palette, parent, false);
            return view;
    }
            return view;
}

第一项的布局(item_choose_color_picture):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

    <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/item_choose_color_image"
            />

    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/item_choose_color_abs"
            >

    </RelativeLayout>

</RelativeLayout>

MainActivity:

itemRelative = (RelativeLayout) ((RelativeLayout) listView.getChildAt(0)).findViewById(R.id.item_choose_color_abs);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = 20;
        layoutParams.leftMargin = 20;
        ImageView view = new ImageView(this);
        view.setImageDrawable(getResources().getDrawable(R.drawable.color_marker));
        view.setLayoutParams(layoutParams);
        itemRelative.addView(view, layoutParams);

更新

当我对main_activity.xml中的RelativeLayout做同样的事情时,一切正常。所有标记都添加到适当的位置。

0 个答案:

没有答案