问题
I have a ListView. When I click on a ListItem, I set the background of the ListItem (it's view) to another color:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
setupDetailView(position);
setupChartView(position);
setupARView(position);
emptyView.setVisibility(View.INVISIBLE);
quotesAdapter.isSelected = true;
//v.setBackgroundResource(R.drawable.stocks_selector);
}
});
here is my adapter:
private class QuoteAdapter extends ArrayAdapter<Quote> {
private ArrayList<Quote> items;
public boolean isSelected = false;
public QuoteAdapter(Context context, int textViewResourceId, ArrayList<Quote> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mainrow, null);
if(isSelected)
v.setBackgroundResource(R.drawable.red);
else
v.setBackgroundResource(R.drawable.transparent_background);
}
The problem is, if I select multiple rows, then multiple rows have a colored background. I only want the clicked item to have a colored background. So if I click on row 2, I want it to turn red, then if I click row 1, I want row 2 to go back to normal, and row 1 to turn red.
How can I do this?
回答1:
Put your list selector in your ListView
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:listSelector="@drawable/stocks_selector" />
your stocks_selector.xml should look something like
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
type="rectangle"
>
<gradient
android:startColor="@color/start_gradient"
android:endColor="@color/end_gradient"
android:angle="270" />
/>
</shape>
来源:https://stackoverflow.com/questions/3808175/listview-selector-problem-selection-does-not-get-removed