highlighting the selected item in the listview in android

前端 未结 4 476
小鲜肉
小鲜肉 2020-11-30 03:21

I am having 1 list view contactslist. I wrote the code for highlighting the selected item in the ListView. It is working. When I click on 1 item it

4条回答
  •  爱一瞬间的悲伤
    2020-11-30 03:37

    ListViews by default don't have a choiceMode set (it's set to none), so the current selection is not indicated visually.

    To change this, you just need to set the choiceMode attribute of your ListView to singleChoice.
    If you'd like custom background for the selected items in your list, you should also set the listSelector attribute. There you can specify not only colors, but drawables (images, layer-/state-drawables).

    
    

    If you don't use a ListView directly, but a ListActivity, then these attributes need to be set from code, so you should extend your activity's onCreate method with these lines:

    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    getListView().setSelector(android.R.color.darker_gray);
    

    So if you were using a click listener to change the background of the selected row, remove that from your code, and use the proper method from above.

    Reply to the update

    If you set the background from your getView method, instead of using a static color, apply a state list drawable to the row background with duplicateParentState set to true. This way it will change its display based on the current state of the item: normal, focused, pressed, etc.

提交回复
热议问题