testsc
testsc

Reputation: 71

Why does Listview scrolling refresh my results?

I'm using a ListView with a custom adapter. On press of a row I am updating the item in the list. But every time I'm scrolling up or down it refills the items in the ListView and changes back to the default value.

This is my class:

class CategoryPreviewClass
{
    public string CategoryName { get; set; }
    public string CategoryID { get; set; }
}

This is the adapter:

public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.CategoryPreview, null, false);

        }


        TextView txtCategoryName = row.FindViewById<TextView>(Resource.Id.txtCategoryName);
        txtCategoryName.Text = mitems[position].CategoryName;
        TextView txtCategoryID = row.FindViewById<TextView>(Resource.Id.txtCategoryID);
        txtCategoryID.Text = mitems[position].CategoryID;

        txtCategoryName.Click += delegate
        {
            txtCategoryName.Text="CustomText";
        };


        return row;
    }

Should I save the changed values on every press of the ListView? Image

Upvotes: 0

Views: 1063

Answers (2)

Billy Liu
Billy Liu

Reputation: 2168

But every time I'm scrolling up or down it refills the items in the ListView and changes back to the default value.

Because of you only change the text in the textview, not the data in mitems. When the listrow is recycled and rebind, it bind data from mitems again. So you need to modified the data in mitems.
For example:

    txtCategoryName.Click += delegate
    {
        txtCategoryName.Text = "CustomText";
        mitems[position].CategoryName = "CustomText";
    };

Upvotes: 0

MezzDroid
MezzDroid

Reputation: 560

You need to create a holder for your adapter so that your items are not recreated every time you scroll.

private class Holder {
    TextView text1;
    TextView text2;
}

And then in your getView method you have to call these textviews by holder name.

For more information refer to this link:

https://www.myandroidsolutions.com/2012/07/19/android-listview-with-viewholder-tutorial/#.WsumLojwZPY

Upvotes: 1

Related Questions