Search code examples
androidadaptertogglebutton

multiple ToggleButton on listView items. When one is clicked, others get turned on/off


I have a list view with several ToggleButton items. When I click one, another gets turned on/off. However, it executes the action related to the right ListView item.

They are managed in a custom adapter, I here is my code:

public class AdapterContacts extends BaseAdapter implements OnClickListener {

ToggleButton btnIsSending;
     .
     .
     .

   public View getView(int position, View convertView, ViewGroup viewGroup) {
    Contact entry = contactsList.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.contact_row, null);
    }
     .
     .
     .
   // isSending button
    btnIsSending = (ToggleButton) convertView.findViewById(R.id.btnIsSending);
    btnIsSending.setFocusableInTouchMode(false);
    btnIsSending.setFocusable(false);
    btnIsSending.setOnClickListener(this);
    btnIsSending.setTag(entry);

    return convertView;
}

    public void onClick(View view) {
    final Contact entry = (Contact) view.getTag();
    Log.d(TAG, "entry " + entry.getPhoneNr());

    LookalizeData lookData = (LookalizeApp.getContext()).lookalizeData;
    // Toggle send button
    if( view.getId() == btnIsSending.getId()){
        if(btnIsSending.isChecked())
             ...
        else
                     ... 
      }       

There are other buttons and they work fine.

Any idea or experience to share?


Solution

  • In your getView you have to something like this (this code is give you an idea how it will work in your case):

    ListView lv = ((ListActivity)context).getListView();
    // Containing all check states
    SparseBooleanArray sba = lv.getCheckedItemPositions();
    
    btnIsSending = (ToggleButton) convertView.findViewById(R.id.btnIsSending);
    btnIsSending.setFocusableInTouchMode(false);
    btnIsSending.setFocusable(false);
    btnIsSending.setTag(entry);
    
    btnIsSending.setChecked(false);
    
    // Cursor is passed as an argument.
    if(sba != null)
      if(sba.get(cursor.getPosition()))
         btnIsSending.setChecked(true);
    

    That said this what you need on the Activity side.

    You have make your ListView to multi-selection mode by android:choiceMode in xml or using setChoiceMode.

    You have to remove your onClick listener on buttons. Whatever you doing in onClick of button, you have to add that logic to the onListItemClick of ListActivtiy.