Set the background when a click is clicked and the background after a click is released for the ListView.
In this example,
(1) the specified background is displayed when you click the item of ListView,
(2) After the ticket is released, the item you just clicked will have a specified background.
Implementation (1) is simple: Set listSelector for ListView in xml.
Implementation (2) is also very simple, and the background is changed dynamically in the adapter:
if (position == selectedPosition){ convertView.setBackgroundResource(R.color.left_selected); }else{ convertView.setBackgroundResource(R.color.left_normal); }
In addition, the selectedPosition is updated in time in the Click Event of the ListView:
LeftLV. setOnItemClickListener (new AdapterView. OnItemClickListener () {@ Override public void onItemClick (AdapterView
Parent, View view, int position, long id) {// update the background color FirstClassAdapter = (FirstClassAdapter) (parent. getAdapter (); adapter. setSelectedPosition (position); adapter. notifyDataSetChanged ();}});
However, the problem arises: After (2) is set, the effect of (1) is gone !!!
This is because, when setting
convertView.setBackgroundResource(R.color.left_selected);
The color specified in listSelector in (1) will be overwritten.
There are two solutions:
(1)
Change a solid color background of convertView to a selector and set the color to transparent when you click it (the listSelector color is displayed below ). The following are selector_left_normal.xml and selector_left_selected.xml.
Then change the code in (2):
if (position == selectedPosition){ convertView.setBackgroundResource(R.drawable.selector_left_selected); }else{ convertView.setBackgroundResource(R.drawable.selector_left_normal); }
(2)
Refer to (1) to remove the listSelector attribute of ListView and copy its color to the two selectors above to replace the transparent color.
That is to say, when you set the background color after clicking the ListView entry,
(A) If the entry is selected, it is set to a color.
(B) Otherwise, set the color to a selector, and specify the color when clicking or not clicking in the selector.
The problem is solved successfully.