0

I am trying to add elements to a ListView dynamically at runtime. Here is my code.

<?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>

The getView function overridden by my adapter

@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;
    }

Now what happens that the first couple of rows seem at jumbled up. Like multiple rows have been added to the same row. What am i doing wrong ?

Kind Regards,

2
  • searchResultsRow is reused, therefore it contains all the items you have already added to it the previous time you used it. Commented Apr 10, 2013 at 15:29
  • so what should i so then ? Commented Apr 10, 2013 at 15:38

2 Answers 2

1

I am wondering if ConvertView != null, linearLayout is not initialed.

Sign up to request clarification or add additional context in comments.

Comments

0

The issue here is that convertView, if not null, is a previously used view, already containing the 4 TextViews.

What you have to do is reuse the existing TextViews from convertView.

One way of doing this is as so: you are inflating categories_row_object. Put your 4 TextView in it, then access it by id.

Or, you could browse the children views of your LinearLayout.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.