Search code examples
androidandroid-listviewtogglebutton

ToggleButton in ListView, value changes automatically on scrolling


I have a ListView with some items. I have toggleButton in each row of the ListView. Assume none of the toggleButtons are selected. The scroll works fine. But when I check the toogleButton, and then scroll my listView, when the selected toggleButton's row moves up, the last toggleButton(which is unchecked) gets checked automatically. And this pattern goes on. I think it has something to do with the reusing the rows of the listItems. I have added the adapter class below, where the list item loads

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View rowview = convertView;
    if (null == rowview) {

        rowview = inflator.inflate(R.layout.groupsettinglistitem, null);            
        SettingsGroupListItem viewholder=new SettingsGroupListItem();
        viewholder.gpname=(TextView) rowview.findViewById(R.id.textView1);
        viewholder.status=(ToggleButton) rowview.findViewById(R.id.ToggleButton1);
        viewholder.status.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
            Toast.makeText(v.getContext(), "click", Toast.LENGTH_SHORT);    
            }
        });

        rowview.setTag(viewholder);

    }
    SettingsGroupListItem holder=(SettingsGroupListItem) rowview.getTag();
    holder.gpname.setText(items[position].getGpname().getText().toString());
    rowview.setTag(holder);
    return rowview;
}

Solution

  • This two Method add in your BaseAdapter class.

              @Override
                public int getViewTypeCount() {                 
                              //Count=Size of ArrayList.
                    return Count;
                }
    
                @Override
                public int getItemViewType(int position) {
    
                    return position;
                }