This article describes the Android implementation of the ListView to set the background when clicking and the background after clicking and letting go. Share it for your reference. The specific analysis is as follows:
The effect to achieve here is,
(1) When clicking the ListView item, there will be a specified background.
(2) After letting go, the item you just clicked will also have a specified background
Implementation (1) is very simple: just set a listSelector for ListView in xml.
android:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:divider="@color/popup_left_bg"
android:dividerHeight="1dp"
android:listSelector="@color/popup_right_bg"
android:scrollingCache="false"
/>
Implementation (2) is also very simple, dynamically change the background in the adapter:
(.left_selected);
}else{
(.left_normal);
}
And update the selectedPosition in time in the click event of the ListView:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Update the background color
FirstClassAdapter adapter = (FirstClassAdapter) (());
(position);
();
}
});
However, the problem arises: after setting (2), the effect of (1) is gone! ! !
This is because, in the settings
When , the color specified in listSelector in (1) will be overwritten.
There are two solutions:
(one)
Change a solid color background of convertView to a selector, and set its color to be transparent when clicked (this will reveal the color of the listSelector below). The following are selector_left_normal.xml and selector_left_selected.xml.
<item android:state_pressed="true"
android:drawable="@android:color/transparent"/>
<item android:state_pressed="false"
android:drawable="@color/popup_left_bg"/>
</selector>
<selector xmlns:andro>
<item android:state_pressed="true"
android:drawable="@android:color/transparent"/>
<item android:state_pressed="false"
android:drawable="@color/popup_right_bg"/>
</selector>
Then change the code in (2) to:
(.selector_left_selected);
}else{
(.selector_left_normal);
}
(two)
Refer to (I), remove the listSelector property of ListView and copy its color to the two selectors above to replace the transparent color.
That is to say, every time you click the ListView entry and set the background color,
(a) If the entry is now selected, set it to a certain color directly
(b) Otherwise, set its color to a selector and specify the colors when clicked and no clicked in the selector respectively.
The problem was solved successfully.
I hope this article will be helpful to everyone's Android programming design.