How can I change the background color for an specific row properly in a ListView? (Android)

前端 未结 7 2018
别那么骄傲
别那么骄傲 2020-12-17 05:05

I have spent some days trying to solve a problem I have with ListViews on Android. I would like to implement a single selection list box using a ListView. So, I would like t

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 05:30

    Yes you should use as Dave said:

    view.setBackgroundColor(SELECTED_COLOR);
    

    and perhaps

    view.refreshDrawableState(); 
    

    however because Android recycle lists, it will repeat your selected colour on every first item which is not shown on the screen. So if your screen size can show ten items than 11th, 21nd etc will be also shown as selected when you scroll.

    To avoid this you have to create a custom adapter. Then in getView you need to say this:

    if (myActivity.selectedRow != position){
        v.setBackgroundColor(Color.TRANSPARENT);
    } else {
        v.setBackgroundColor(SELECTED_COLOUR);
    }
    

    Where selectedRow is a public static int selectedRow within myActivity, the activity which creates your list. There you store the row number which is selected when clicking the list.

提交回复
热议问题