How to change the color of a selected item in a listview?



I need to change the color of a selected item in a ListView when its clicked, so the user know what has clicked.


So far I have done this code for that:



listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int a = 0; a< parent.getChildCount();a++){
parent.getChildAt(a).setBackgroundColor(Color.TRANSPARENT);
view.refreshDrawableState();
if(parent.getChildAt(a) == view){
view.setBackgroundColor(getResources().getColor(R.color.soft_opaque));
view.refreshDrawableState();
}
}


What it does is to change the background color of the item selected and keep it like that until I click another item so it change only the current item selected background color


I also was wondering if there is an XML way to do it. What I've found so far is:



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://ift.tt/nIICcg">
<item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
<item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
<item android:drawable="@color/black" /> <!-- default -->
</selector>


but haven't got what I the previous code does.


No comments:

Post a Comment