ListView item won't stay “selected”

后端 未结 10 1332
暗喜
暗喜 2020-12-10 05:50

I want to change the background of a listview item when the user clicks it. Kind of like the Honeycomb settings page (Although I\'m not dealing with just settings so I\'m no

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 06:44

    The android state checked is best used to resolve this issue.

    Someone mentioned using android:background="?android:attr/activatedBackgroundIndicator".

    This just points to one of the activated_background_* resources in frameworks/base/core/res/res/drawable of the android source code. For example activated_background_holo_dark.xml:

     
      
       
    
    

    So essentially you want to use state_activated to represent when the user presses the button as well when it is in a checked (i.e. in a persistent selected state) state. Note that activated was only introduced after Honeycomb, if you are targeting older devices you'll need to rely on state_checked (more details here).

    Now if you want to set an item as checked, you need to call listView.setItemChecked(position, true). You'll likely want to set the android:choiceMode property on your ListView to the appropriate value (e.g. if you want only one thing selected at a time use singleChoice). You don't need to invalidate, the call to setItemChecked will trigger a relayout which will update the view.

    Also be careful if you allow reordering items in your ListView as the current checked item(s) will need to be updated. If you use stable Ids, this will be handled automatically.

    To see an example of this in action, check out the NavigationDrawer sample code found in the training series: http://developer.android.com/training/implementing-navigation/nav-drawer.html.

提交回复
热议问题