首页 > 移动平台 > 详细

android中定义一个可勾选的ListView

时间:2014-10-24 18:07:13      阅读:302      评论:0      收藏:0      [点我收藏+]

1、在layout中定义一个CheckedTextView

<CheckedTextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checkMark="?android:attr/listChoiceIndicatorMultiple"
            android:gravity="center_vertical"
            android:text="Full Name"
            android:textColor="#000" />

2、定义一个Adapter,里面维护一个SpraseBooleanArray,每次getView()时,会根据SpraseBooleanArray里面存储的值设置check状态

class MyAdapter extends BaseAdapter {
        //这个数组中记录着被勾选项的状态
    private SparseBooleanArray mCheckedTable;
   
    public MyAdapter() {
        mCheckedTable = new SparseBooleanArray();
        //其他代码
        }

3、在adapter的getView()方法中,根据SparseBooleanArray中的值来设置checked状态

public View getView(int position, View convertView, ViewGroup parent) {
        CheckedTextView checkedView = convertView.findViewById(R.id.textView1);
    checkedView.setChecked(mCheckedTable.get(position));
    //其他代码
}

4、设置一个OnItemClickListener,当列表项被点击时,执行CheckedTextView.toggle()方法,将状态转换过来。

5、并把CheckedTextView的新状态以及位置(位置为key,状态为value)加入array中

myListView.setOnItemClickListener(new OnItemClickListener() {
   
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                MyAdapter adapter = (MyAdapter) parent.getAdapter();
                CheckedTextView name = (CheckedTextView) view.findViewById(R.id.textView1);
                name.toggle();
                //put the checked item position into boolean array
                    adapter.getCheckedTable().put(position, name.isChecked());
                   
            }
        });

所有被选中的项目信息,都在SpraseBooleanArray中,可以通过一个index和for循环,依次从中取出数据(使用keyAt()和valueAt()方法)。Value为true的key,即对应被选中的item.

android中定义一个可勾选的ListView

原文:http://www.cnblogs.com/a354823200/p/4048581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!