利用listview原生的方法麦到,實現(xiàn)列表單選
1. 在布局文件中添加android:choiceMode="singleChoice"
<ListView
android:id="@+id/lv_no_jiaru"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@color/line_com_top"
android:dividerHeight="0.5dp"
android:choiceMode="singleChoice"
android:listSelector="@color/white"
android:scrollbars="none" />
或者在java代碼中添加
lvNoJiaru.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 設置listview單選
lvNoJiaru.setAdapter(relatedJobAdapter);
重點,setChoiceMode要放在setAdapter方法之前
2.在listview的點擊事件中這么寫
lvNoJiaru.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
lvNoJiaru.setItemChecked(i, true);//設置選中的item
relatedJobAdapter.notifyDataSetChanged();// 通知adapter刷新布局
}
});
3.在adapter中這么寫
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_related_job, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// 通過isItemChecked方法,判斷哪一個item被選中,然后進行相關邏輯處理
if (this.listView.isItemChecked(position)) {
holder.radioCheck.setChecked(true);
} else {
holder.radioCheck.setChecked(false);
}
return convertView;
}
OK,搞定
效果如圖所示