我有一个ListView。当我单击ListItem时,我将ListItem(它的视图)的背景设置为另一种颜色:
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);
}
});
这是我的适配器:
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);
}
问题是,如果我选择多行,则多行具有彩色背景。我只希望点击的项目有彩色背景。因此,如果我点击第2行,我希望它变为红色,那么如果我点击第1行,我希望第2行恢复正常,第1行变为红色。
我该怎么做?
答案 0 :(得分:2)
将列表选择器放入ListView
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:listSelector="@drawable/stocks_selector" />
您的stocks_selector.xml应该类似于
<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>