自定义单选ListView

来源:互联网 发布:sqlserver 服务器名称 编辑:程序博客网 时间:2024/07/24 02:32

1.item布局实现Checkable接口

public class ChoiceView extends LinearLayout implements Checkable {    TextView tvRepeatTitle;    ImageView ivCheckIcon;    public ChoiceView(Context context) {        super(context);        View.inflate(context, R.layout.item_repeat_item, this);        tvRepeatTitle = (TextView) findViewById(R.id.tv_repeat_title);        ivCheckIcon = (ImageView) findViewById(R.id.iv_check_icon);    }    public void setText(String text) {        tvRepeatTitle.setText(text);    }    @Override    public void setChecked(boolean checked) {        if (checked) {            ivCheckIcon.setVisibility(View.VISIBLE);        } else {            ivCheckIcon.setVisibility(View.INVISIBLE);        }    }    @Override    public boolean isChecked() {        return ivCheckIcon.getVisibility() == VISIBLE;    }    @Override    public void toggle() {        Log.w("ChoiceView", "toggle()");    }}

2.将ListView设置为CHOICE_MODE_SINGLE

lvRepeat.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);ListAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.item_repeat_item, repeatArray) {    @Override    public View getView(int position, View convertView, ViewGroup parent) {        final ChoiceView view;        if (convertView == null) {            view = new ChoiceView(getApplicationContext());        } else {            view = (ChoiceView) convertView;        }        view.setText(getItem(position));        return view;    }};lvRepeat.setAdapter(listAdapter);
0 0
原创粉丝点击