曾经在项目中遇到过类似的问题。需要修改item子项的背景,达到互斥效果。
首先,写出自己的适配器。Adapter
这里以GridView为目标
1.适配器,每个人的适配器不尽相同,此为我自己写的。
关键代码。
为:
此处就是处理更换背景的代码。在Adapter中的getView方法中可以找到
if( getSelectIndex() == position ){
viewHolder.item_imageView.setVisibility(View.VISIBLE);
}else{
viewHolder.item_imageView.setVisibility(View.GONE);
}
********************************************************************************************
public class FamousteacherAdapterextends BaseAdapter {
private ArrayList<HashMap<String, Object>>dataList;
private Context context;
private LayoutInflater lf;
private ViewHolder viewHolder = null;
privateint selectIndex = -1;
public int getSelectIndex() {
returnselectIndex;
}
public void setSelectIndex(int selectIndex) {
this.selectIndex = selectIndex;
}
public FamousteacherAdapter(Context context,
ArrayList<HashMap<String, Object>> dataList) {
this.context = context;
this.dataList = dataList;
lf = LayoutInflater.from(context);
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int arg0) {
return dataList.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(finalint position, View convertView, ViewGroup parent) {
if (null == convertView) {
viewHolder =new ViewHolder();
convertView = lf.inflate(R.layout.settingtopic_list, null);
viewHolder.item_textview = (TextView) convertView
.findViewById(R.id.item_textview);
viewHolder.item_imageView = (ImageView) convertView
.findViewById(R.id.item_imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if( getSelectIndex() == position ){
viewHolder.item_imageView.setVisibility(View.VISIBLE);
}else{
viewHolder.item_imageView.setVisibility(View.GONE);
}
Map map = dataList.get(position);
viewHolder.item_textview.setText( (CharSequence) map.get("itemText"));
return convertView;
}
class ViewHolder {
TextView item_textview;
ImageView item_imageView;
}
}
2.第二步,在你的Activity中,你要实现点击事件。
在点击事件中将点击item的Position传回适配器中。然后通知适配器数据有变化。然后效果就达到了。
famous_course_gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(famousteacherAdapter.getSelectIndex()==-1)
{
famousteacherAdapter.setSelectIndex(arg2);
}
else
{
famousteacherAdapter.setSelectIndex(arg2);
}
famousteacherAdapter.notifyDataSetInvalidated();//一定别忘了写这句。
}
});