Android listview toggle button

后端 未结 2 1259
梦谈多话
梦谈多话 2021-01-16 06:50

I have a Listview that will list the alarms which are in the database.I need to add a Toggle Button beside each list item to set the alarm on/off

2条回答
  •  盖世英雄少女心
    2021-01-16 07:19

    There is no small snippet ans. to your problem. I assume you need to have multi-selection. Now here are the things you need.

    Since you are using SimpleCursorAdapter, you should replace that with CursorAdapter. To do so you have to extend it as it is a abstract adapter. Once you done that you will be overriding two functions.

    • newView Where you will create your list item views by inflating R.layout.alarm_row (it should contain your toggle button too). You have make toggle button non-clickable.
    • bindView where you will set state of toggle button and text for your text view

    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.

    Now bindView will look like:

    ListView lv = ((ListActivity)context).getListView();
    // Containing all check states
    SparseBooleanArray sba = lv.getCheckedItemPositions();
    
    
    // I am using check box
    
    cb.setChecked(false);
    
    // Cursor is passed as an argument.
    if(sba != null)
      if(sba.get(cursor.getPosition()))
         cb.setChecked(true);
    

    Ref to docs:

    CursorAdapter docs

    http://developer.android.com/reference/android/widget/ListView.html

提交回复
热议问题