0

我试图在运行时动态地将元素添加到 ListView。这是我的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/category_row"
    android:orientation="horizontal" >
    <!-- Contents will be added at Runtime -->
</LinearLayout>

我的适配器覆盖的 getView 函数

@Override
    public View getView(final int position, final View convertView,
            final ViewGroup parent) {
        View searchResultsRow = convertView;
        LinearLayout linearLayout;
        TextView e1,e2,e3,e4;
        if (searchResultsRow == null) {
            LayoutInflater layoutInflator = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            searchResultsRow = layoutInflator.inflate(
                    R.layout.categories_row_object, null);
            linearLayout = (LinearLayout) searchResultsRow.findViewById(R.id.category_row);

        }
        e1 = new TextView(context);
        e2 = new TextView(context);
        e3 = new TextView(context);
        e4 = new TextView(context);

        e1 = new TextView(context);
        e1.setText("Fashion");
        linearLayout.addView(e1);

        e2 = new TextView(context);
        e2.setText("Men");
        linearLayout.addView(e2);

        e3 = new TextView(context);
        e3.setText("Casual Wear");
        linearLayout.addView(e3);


        e4 = new TextView(context);
        e4.setText("Jeans");
        linearLayout.addView(e4);


        return searchResultsRow;
    }

现在,前几行似乎混乱了会发生什么。就像多行已添加到同一行。我究竟做错了什么 ?

亲切的问候,

4

2 回答 2

1

我想知道 ConvertView != null, linearLayout 是否没有初始化。

于 2013-04-10T15:44:09.640 回答
0

这里的问题是convertView,如果不是 null,它是以前使用的视图,已经包含 4 TextViews

您要做的是重用现有的TextViewsfrom convertView

这样做的一种方法是:你正在膨胀categories_row_object. 把你的 4 放进TextView去,然后通过 id 访问它。

或者,您可以浏览您的LinearLayout.

于 2013-04-11T07:52:08.253 回答