Xamarin/Android: Use ViewHolder In BaseAdapter Class

I was having a lot problem with Android ListView using Adapters lately. The original implementation was horrible causing the ListView to generate a lot of duplicate item.

Purpose of Code: I had this checklist page where it supposed to load a list of checklist item from server database and populate the item into ListView on the app.

1. Original code.
Problem Description: the display is weird and it’s causing display of duplicate items here and there.

...
public override View GetView(int position, View view, ViewGroup parent)
{
    GetChecklistItem cli = checklistItems[position];

    if (view != null)
        return view;
    if (view == null)
    {
        view = context.LayoutInflater.Inflate(AnacleAndroid.Resource.Layout.ChecklistRow, null);
    }

    TextView objectName = (TextView)view.FindViewById(AndroidApp.Resource.Id.lblObjectName);
    EditText remarks = (EditText)view.FindViewById(AndroidApp.Resource.Id.checklistRemarks);
    RadioGroup radio = (RadioGroup)view.FindViewById(AndroidApp.Resource.Id.radioGroup);
    objectName.Text = cli.ObjectName;
    if (cli.ChecklistType.HasValue)
    {
        if (cli.HasSingleTextboxField == 1 || cli.ChecklistType == ChecklistItemType.Remarks || cli.ChecklistType == ChecklistItemType.SingleLineFreeText)
        {
            remarks.Visibility = ViewStates.Visible;
            remarks.Text = cli.Remarks;
            remarks.TextChanged += delegate(object sender, Android.Text.TextChangedEventArgs e)
            {
                editChecklist.RemarksTextChangedClick(sender, e, cli);
            };
        }
        else
        {
            // otherwise hide the remark control
            remarks.Visibility = ViewStates.Gone;
        }
        if (cli.ChecklistType == ChecklistItemType.Choice)
        {
            // If checklist type is a choice. Split the ResponseName string and create radio button for each response for user to select
            //radio.
            string[] noOfRb = cli.ResponseName.Split(',');
            foreach (string tempRb in noOfRb)
            {
                RadioButton newRb = new RadioButton(this.context);
                newRb.Text = tempRb;
                newRb.TextSize = 16;
                newRb.Checked = (cli.SelectedResponse != null && cli.SelectedResponse.Equals(tempRb.Trim()));
                newRb.Click += delegate(object sender, EventArgs e)
                {
                    editChecklist.RadioButtonClick(sender, e, cli);
                };
                radio.AddView(newRb, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
            }
        }
        else
        {
            // Otherwise hide the RadioGroup control
            radio.Visibility = ViewStates.Gone;
        }
    }
    return view;
}
...

After Googling around, I found some answers. It has something to the Android always repainting the ListView. So I have to have a a way to store the control without the android having to look up for control every time it trigger the GetView(…). And the answer is ViewHolder. For more details please refer to this URL.

2. Fix 1 Using ViewHolder
Problem Description: 
The dynamic radio button keep duplicating like crazy every time user scroll up or down.

// ViewHolder Class
private class ViewHolderItem : Java.Lang.Object
{
	public TextView ObjectName;
	public EditText Remarks;
	public RadioGroup Options;
}
...
public override View GetView(int position, View view, ViewGroup parent)
{
	ViewHolderItem viewHolder;
	
	if (view == null)
	{
		view = context.LayoutInflater.Inflate(AnacleAndroid.Resource.Layout.ChecklistRow, null);
		viewHolder = new ViewHolderItem();
		viewHolder.ObjectName = (TextView)view.FindViewById(AnacleAndroid.Resource.Id.lblObjectName);
		viewHolder.Remarks = (EditText)view.FindViewById(AnacleAndroid.Resource.Id.checklistRemarks);
		viewHolder.Options = (RadioGroup)view.FindViewById(AnacleAndroid.Resource.Id.radioGroup);

		view.Tag = viewHolder;
	}
	else
	{
		viewHolder = (ViewHolderItem)view.Tag;
	}
	
	GetChecklistItem cli = checklistItems[position];
	
	if (cli != null)
	{
		viewHolder.ObjectName.Text = cli.ObjectName;
		viewHolder.ObjectName.Tag = cli.ObjectID;
		viewHolder.Remarks.Visibility = ViewStates.Visible;
		viewHolder.Options.Visibility = ViewStates.Visible;

		if (cli.ChecklistType.HasValue)
		{
			if (cli.HasSingleTextboxField == 1 || cli.ChecklistType == ChecklistItemType.Remarks || cli.ChecklistType == ChecklistItemType.SingleLineFreeText)
			{
				viewHolder.Remarks.Visibility = ViewStates.Visible;
				viewHolder.Remarks.Text = cli.Remarks;
				viewHolder.Remarks.TextChanged += delegate(object sender, Android.Text.TextChangedEventArgs e)
				{
					editChecklist.RemarksTextChangedClick(sender, e, cli);
				};
			}
			else
				viewHolder.Remarks.Visibility = ViewStates.Gone;
		}

		if (cli.ChecklistType == ChecklistItemType.Choice)
		{
			//radio.
			string[] noOfRb = cli.ResponseName.Split(',');

			foreach (string tempRb in noOfRb)
			{
				RadioButton newRb = new RadioButton(this.context);
				newRb.Text = tempRb;
				newRb.TextSize = 16;
				newRb.Checked = (cli.SelectedResponse != null && cli.SelectedResponse.Equals(tempRb.Trim()));
				newRb.Click += delegate(object sender, EventArgs e)
				{
					editChecklist.RadioButtonClick(sender, e, cli);
				};
				viewHolder.Options.AddView(newRb, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
			}
		}
		else
			viewHolder.Options.Visibility = ViewStates.Gone;
	}
	
	return view;
}
...

So then I tried moving the value and assignment and radio button creation into the view building if section.

3. Fix 2 Using ViewHolder
Problem Description: Yay! the radio button duplication problem disappears. However, another problem pops out right away. It turns out this fix causes the listview to display not in order of the item list stored. And the order keeps getting messed up every time I scroll up or down.

// ViewHolder Class
private class ViewHolderItem : Java.Lang.Object
{
	public TextView ObjectName;
	public EditText Remarks;
	public RadioGroup Options;
}
...
public override View GetView(int position, View view, ViewGroup parent)
{
	ViewHolderItem viewHolder;
	GetChecklistItem cli = checklistItems[position];
	if (view == null)
	{
		view = context.LayoutInflater.Inflate(AnacleAndroid.Resource.Layout.ChecklistRow, null);
		viewHolder = new ViewHolderItem();
		viewHolder.ObjectName = (TextView)view.FindViewById(AnacleAndroid.Resource.Id.lblObjectName);
		viewHolder.Remarks = (EditText)view.FindViewById(AnacleAndroid.Resource.Id.checklistRemarks);
		viewHolder.Options = (RadioGroup)view.FindViewById(AnacleAndroid.Resource.Id.radioGroup);
		
		if (cli != null)
		{
			viewHolder.ObjectName.Text = cli.ObjectName;
			viewHolder.ObjectName.Tag = cli.ObjectID;
			viewHolder.Remarks.Visibility = ViewStates.Visible;
			viewHolder.Options.Visibility = ViewStates.Visible;

			if (cli.ChecklistType.HasValue)
			{
				if (cli.HasSingleTextboxField == 1 || cli.ChecklistType == ChecklistItemType.Remarks || cli.ChecklistType == ChecklistItemType.SingleLineFreeText)
				{
					viewHolder.Remarks.Visibility = ViewStates.Visible;
					viewHolder.Remarks.Text = cli.Remarks;
					viewHolder.Remarks.TextChanged += delegate(object sender, Android.Text.TextChangedEventArgs e)
					{
						editChecklist.RemarksTextChangedClick(sender, e, cli);
					};
				}
				else
					viewHolder.Remarks.Visibility = ViewStates.Gone;
			}

			if (cli.ChecklistType == ChecklistItemType.Choice)
			{
				//radio.
				string[] noOfRb = cli.ResponseName.Split(',');

				foreach (string tempRb in noOfRb)
				{
					RadioButton newRb = new RadioButton(this.context);
					newRb.Text = tempRb;
					newRb.TextSize = 16;
					newRb.Checked = (cli.SelectedResponse != null && cli.SelectedResponse.Equals(tempRb.Trim()));
					newRb.Click += delegate(object sender, EventArgs e)
					{
						editChecklist.RadioButtonClick(sender, e, cli);
					};
					viewHolder.Options.AddView(newRb, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
				}
			}
			else
				viewHolder.Options.Visibility = ViewStates.Gone;
		}

		view.Tag = viewHolder;
	}
	else
	{
		viewHolder = (ViewHolderItem)view.Tag;
	}
	
	return view;
}
...

Solution Description: The problem again turns out to have something to do with the repainting of the android ListView during scrolling. The value setting and building of radio buttons has to be after the view initialization if-else. So then I figured it out! Since the view is stored means the radio button created dynamically added into the RadioGroup will also be stored. Then if the scrolling causing the repainting calling the GetView again it will trigger another another radio button creation and add into RadioGroup without removing the previous Radio button. So the magic was just to clear all child view in the Options RadioGroup before adding the Radio Button.

4. Final Fix Using ViewHolder. (Full Code)

public class ChecklistAdapter : BaseAdapter<GetChecklistItem>
{
    private class ViewHolderItem : Java.Lang.Object
    {
        public TextView ObjectName;
        public EditText Remarks;
        public RadioGroup Options;
    }

    List<GetChecklistItem> checklistItems;
    Activity context;
    EditChecklist editChecklist;
    
    public ChecklistAdapter(Activity context, List<GetChecklistItem> newList) : base()
    {
        this.context = context;
        this.checklistItems = newList;
        editChecklist = (EditChecklist)context;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override GetChecklistItem this[int position]
    {
        get { return checklistItems[position]; }
    }
    public override int Count
    {
        get { return checklistItems.Count; }
    }

    public override View GetView(int position, View view, ViewGroup parent)
    {
        ViewHolderItem viewHolder;

        if (view == null)
        {
            view = context.LayoutInflater.Inflate(AnacleAndroid.Resource.Layout.ChecklistRow, null);
            viewHolder = new ViewHolderItem();
            viewHolder.ObjectName = (TextView)view.FindViewById(AndroidApp.Resource.Id.lblObjectName);
            viewHolder.Remarks = (EditText)view.FindViewById(AndroidApp.Resource.Id.checklistRemarks);
            viewHolder.Options = (RadioGroup)view.FindViewById(AndroidApp.Resource.Id.radioGroup);

            view.Tag = viewHolder;
        }
        else
        {
            viewHolder = (ViewHolderItem)view.Tag;
        }

        GetChecklistItem cli = checklistItems[position];

        if (cli != null)
        {
            viewHolder.ObjectName.Text = cli.ObjectName;
            viewHolder.ObjectName.Tag = cli.ObjectID;
            viewHolder.Remarks.Visibility = ViewStates.Visible;
            viewHolder.Options.Visibility = ViewStates.Visible;

            if (cli.ChecklistType.HasValue)
            {
                if (cli.HasSingleTextboxField == 1 || cli.ChecklistType == ChecklistItemType.Remarks || cli.ChecklistType == ChecklistItemType.SingleLineFreeText)
                {
                    viewHolder.Remarks.Visibility = ViewStates.Visible;
                    viewHolder.Remarks.Text = cli.Remarks;
                    viewHolder.Remarks.TextChanged += delegate(object sender, Android.Text.TextChangedEventArgs e)
                    {
                        editChecklist.RemarksTextChangedClick(sender, e, cli);
                    };
                }
                else
                    viewHolder.Remarks.Visibility = ViewStates.Gone;
            }

            if (cli.ChecklistType == ChecklistItemType.Choice)
            {
                //radio.
                string[] noOfRb = cli.ResponseName.Split(',');
				
				// important to remove all vew under the view group before repopulating it
                if (viewHolder.Options != null && viewHolder.Options.ChildCount > 0)
                    viewHolder.Options.RemoveAllViews();

                foreach (string tempRb in noOfRb)
                {
                    RadioButton newRb = new RadioButton(this.context);
                    newRb.Text = tempRb;
                    newRb.TextSize = 16;
                    newRb.Checked = (cli.SelectedResponse != null && cli.SelectedResponse.Equals(tempRb.Trim()));
                    newRb.Click += delegate(object sender, EventArgs e)
                    {
                        editChecklist.RadioButtonClick(sender, e, cli);
                    };
                    viewHolder.Options.AddView(newRb, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
                }
            }
            else
                viewHolder.Options.Visibility = ViewStates.Gone;
        }
        
        return view;
    }

    public override void NotifyDataSetChanged()
    {
        base.NotifyDataSetChanged();
    }
}
Advertisements
Xamarin/Android: Use ViewHolder In BaseAdapter Class

One thought on “Xamarin/Android: Use ViewHolder In BaseAdapter Class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s