我有自定义适配器的列表视图。列表视图中唯一的项目是TextView(现在)。当我单击TextView时,背景颜色应该变为蓝色,当我再次单击它时,背景颜色应该更改为默认颜色(浅灰色)。我试图使用ViewHolder Pattern实现这一点。
现在的问题是,当我点击列表中的第一项时,一些随机项的背景颜色变为蓝色。
CustomAdapter类:
public class ResultsAdapter extends BaseAdapter {
ViewHolder holder;
@Override
public int getCount() {
return dummyText.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.item_mtf_results, parent, false);
holder = new ViewHolder();
holder.txtViewResults = (TextView) convertView
.findViewById(R.id.textview_item_mtf_results);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewResults.setText(dummyText[position]);
holder.txtViewResults.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(Const.DEBUG, "in onClick Method");
Log.d(Const.DEBUG, "Is checked ? = " + holder.isChecked);
String result = holder.txtViewResults.getText().toString();
listener.onResultClick(result);
if (holder.isChecked) {
Log.d(Const.DEBUG, "isChecked = true");
holder.txtViewResults.setBackgroundColor(getResources()
.getColor(R.color.light_grey));
holder.txtViewResults.setTextColor(getResources()
.getColor(R.color.black));
holder.isChecked = false;
Log.d(Const.DEBUG,
"Holder is set to false.. checked ? = "
+ holder.isChecked);
} else {
Log.d(Const.DEBUG, "isChecked = false");
holder.txtViewResults.setBackgroundColor(getResources()
.getColor(R.color.blue));
holder.txtViewResults.setTextColor(getResources()
.getColor(R.color.white));
holder.isChecked = true;
Log.d(Const.DEBUG,
"Holder is set to true.. checked ? = "
+ holder.isChecked);
}
}
});
return convertView;
}
}
ViewHolder类:
public static class ViewHolder {
TextView txtViewResults;
boolean isChecked = false;
}
如果您需要任何其他代码,请告诉我......
答案 0 :(得分:0)
尝试在converview==null
块内添加文本视图的单击侦听器。每次滚动列表视图时都会设置监听器。