之前做点击事件时,总是做不好,点着点着所有的Item都变色了,隔壁同事给我说了这方法后,我感觉还挺好用,记录下
这是设置的适配器,直接把代码贴出来了
private class DayAdapter extends BaseAdapter {
//首先设置一个变量,因为最初没有选择任何Item,所以我设为-1了,如果默认是第一个,也可以设为0
private int selectedId = -1;
@Override
public int getCount() {
return timeMapList.length();
}
@Override
public Object getItem(int position) {
return timeMapList.optJSONObject(position).optString("desc");
}
@Override
public long getItemId(int position) {
return position;
}
//这里新写一个方法,用来设置选中的id
public void setSelectedId(int position) {
selectedId = position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TextView day;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.shareorder_daylist, null);
day = (TextView) convertView.findViewById(R.id.shareorder_text);
convertView.setTag(day);
} else
day = (TextView) convertView.getTag();
day.setText(timeMapList.optJSONObject(position).optString("desc"));
//如果selectedId是当前选择的position,则设置背景及字体颜色
if (selectedId == position) {
day.setBackgroundColor(Color.WHITE);
day.setTextColor(Color.parseColor("#f53331"));
} else {
day.setBackgroundColor(Color.TRANSPARENT);
day.setTextColor(Color.BLACK);
}
return convertView;
}
}
接下来只要在点击事件设置一下id,然后刷新数据就可以了
DayAdapter dayAdapter = new DayAdapter();
listviewDay.setAdapter(dayAdapter);
listviewDay.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//将当前选中的position设置为选中的id
dayAdapter.setSelectedId(position);
//千万不要忘了刷新数据
dayAdapter.notifyDataSetInvalidated();
}
});