ListView的选中状态的实现实际上是点击时刷新Listview 将点击行设置为高亮显示,其他行刷新设置为原来的状态。
本文的ListView中是一个简单的TextView ,为TextView设置一个Selector 设置普通状态和选中状态。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/dialog_text_select" android:state_enabled="false"></item>
<item android:drawable="@android:color/transparent" android:state_enabled="true"></item>
</selector>
Item的写法和一般的没有区别,将android:background设置为上面的Selector就行了。
Adapter需要设置选中的位置:
public class KnowledgeAdapter extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private List<KnowledgeInfo> listKnowledgeInfo;
//当前选中的位置
private int curPos;
public KnowledgeAdapter(Context context, List<KnowledgeInfo> listKnowledgeInfo,int curPos) {
this.context = context;
this.inflater = LayoutInflater.from(context);
this.listKnowledgeInfo = listKnowledgeInfo;
this.curPos = curPos;
}
/**
* 设置当前选中的视图
* @param curPro 选中位置
*/
public void setCurPro(int curPro){
this.curPos = curPro;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listKnowledgeInfo.size();
}
@Override
public KnowledgeInfo getItem(int position) {
// TODO Auto-generated method stub
return listKnowledgeInfo.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
// public ViewHolder getItemView(int position){
// return null;
// }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.knowledge_item, null);
viewHolder.textKnowledeg = (TextView) convertView.findViewById(R.id.knowledge_text);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
//填充数据
viewHolder.textKnowledeg.setText(listKnowledgeInfo.get(position).getName());
if(curPos == position)
viewHolder.textKnowledeg.setEnabled(false);
else
viewHolder.textKnowledeg.setEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView textKnowledeg;
}
}
然后对监听事件进行处理,每次点击都必须重新刷新整个ListView
listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
curPos1 = position;
knowledgeAdapter1.setCurPro(curPos1);
refreshKnowledge();
knowledgeAdapter1.notifyDataSetChanged();
}
});
大致效果图如下