如何检查android中列表中的所有复选框

时间:2014-11-03 09:33:18

标签: android checkbox set

我在代码中遇到一个问题,我在列表视图中使用复选框,并且我有另一个检查设置检查并取消选中我的列表中的所有复选框,目前我可以检查所有项目& #39;但问题是它只显示所有复选框,并返回检查了多少个复选框。 主文件:  公共类Take1扩展了活动{

    EditText dataf,ed2,topic;
    ListView lv;
    Spinner sp,datesp,classno;
    ArrayList<String> al;
    ArrayAdapter<String> ad,ad2;
    ListAdapter adapter;
    String spitem;
    Button speak,date,from,to;
    MediaRecorder mrecorder;
    static final int check=111;
    private static final int DATE_DIALOG_ID = 0;
    private static final int FROM_TIME = 1;
    private static final int TO_TIME = 2;
    int total,pre,ab,cal=0;
    TextView present;
    //database
    SQLiteDatabase db;
    Cursor cr;
    CheckBox checkall;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.take);
        topic=(EditText)findViewById(R.id.taketopic);
        sp=(Spinner)findViewById(R.id.takespinner1);
        datesp=(Spinner)findViewById(R.id.takedatespinner2);
        classno=(Spinner)findViewById(R.id.noofperiods);
        speak=(Button)findViewById(R.id.takespeak);
        date=(Button)findViewById(R.id.takedatebutton);
        from=(Button)findViewById(R.id.takefrom);
        to=(Button)findViewById(R.id.taketo);
        lv=(ListView)findViewById(R.id.takelistview);
        al=new ArrayList<String>();
        present=(TextView)findViewById(R.id.present);
        present.setVisibility(View.GONE);
        ad=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,al);
        ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        checkall=(CheckBox)findViewById(R.id.checkall);
        datesp.setVisibility(View.GONE);
        //checkall.setVisibility(View.GONE);

        assign();

        //database
        db=SQLiteDatabase.openOrCreateDatabase("/sdcard/Attendance/database.db",null);



        sp.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                // TODO Auto-generated method stub
                spitem=(String)sp.getItemAtPosition(arg2);
                final ArrayList<String> ss= new ArrayList<String>();

                SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase("/sdcard/Attendance/database.db",null);
                Cursor cr = db.rawQuery("select numbers from Main where class='"+spitem+"'", null);
                if(cr!=null)
                {
                    if(cr.moveToFirst())
                    {
                        do{
                            String pp =cr.getString(cr.getColumnIndex("numbers"));
                            String[]  pp1=pp.split(",");
                            for(int i=0; i<pp1.length;i++)
                            {
                                ss.add(pp1[i]);
                            }
                            Log.e("data",cr.getString(cr.getColumnIndex("numbers")));
                        }while(cr.moveToNext());
                    }
                }
                Toast.makeText(getApplicationContext(),"spitem="+spitem,Toast.LENGTH_SHORT).show();

                adapter=new ListAdapter(getApplicationContext(),1, 0,ss);
                lv.setAdapter(adapter);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

        setlist();



    }

ListAdapter文件:

public class ListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<HashMap<String,Object>> listData;

    public ListAdapter(Context context, int i, int i1, List<String> objects) {
        this.context=context;
        listData =new ArrayList<HashMap<String, Object>>();
        for(String value : objects){
            HashMap<String,Object> row = new HashMap<String, Object>();
            row.put("value",value);
            row.put("isChecked",Boolean.valueOf(false));
            listData.add(row);
        }
    }

    public int selectedItemsSize(){
        int size = 0;
        for(HashMap<String,Object> row : listData){
            if((Boolean)row.get("isChecked")){
                size++;
            }
        }
        return size;
    }

    public ArrayList<String>  getSelected(){
        ArrayList<String> selected = new ArrayList<String>();
        for(HashMap<String,Object> row : listData){
            if((Boolean)row.get("isChecked")){
                selected.add(row.get("value").toString());
            }
        }
        return selected;
    }

    public void checkAll(){
        for(HashMap<String,Object> row : listData){
            row.put("isChecked",true);
        }
        notifyDataSetChanged();
    }
    public void uncheckAll(){
        for(HashMap<String,Object> row : listData){
            row.put("isChecked",false);
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            holder = new Holder();
            convertView = LayoutInflater.from(context).inflate(R.layout.list_row, null);
            holder.tv = (TextView)convertView.findViewById(R.id.listrowtext);
            holder.ckbox =(CheckBox)convertView.findViewById(R.id.listrowcheckBox);

            convertView.setTag(holder);
        }
        else{
            holder = (Holder) convertView.getTag();
        }


        holder.tv.setText(listData.get(position).get("value").toString());
        holder.ckbox.setChecked((Boolean) listData.get(position).get("value"));
        holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                listData.get(position).put("isChecked",isChecked);
                notifyDataSetChanged();
            }
        });


        return convertView;
    }


    static class Holder
    {
        TextView tv;
        CheckBox ckbox;
    }

}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">

    <TextView
        android:id="@+id/listrowtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:text="Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <CheckBox
        android:id="@+id/listrowcheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:text="" />

</RelativeLayout>

模拟器日志报告: 致命的例外:主要

java.lang.ClassCastException: java.lang.String
at works.Attendance.ListAdapter.getView(ListAdapter.java:101)
at android.widget.AbsListView.obtainView(AbsListView.java:1430)
at android.widget.ListView.makeAndAddView(ListView.java:1745)
at android.widget.ListView.fillDown(ListView.java:670)
at android.widget.ListView.fillFromTop(ListView.java:727)
at android.widget.ListView.layoutChildren(ListView.java:1598)
at android.widget.AbsListView.onLayout(AbsListView.java:1260)
at android.view.View.layout(View.java:7175)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
at android.view.View.layout(View.java:7175)
at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
at android.view.View.layout(View.java:7175)
at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
at android.view.View.layout(View.java:7175)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1140)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

获取HashMap的ArrayList,它包含列表字符串值以及列表项检查状态 并定义checkAll和uncheck所有两个自定义方法以检查所有并取消选中所有列表项,根据项位置更改OnCheckedChangeListener上的列表项检查状态。

public class ListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<HashMap<String,Object>> listData;

    public ListAdapter(Context context,List<String> objects) {
        this.context=context;
        listData =new ArrayList<HashMap<String, Object>>();
        for(String value : objects){
            HashMap<String,Object> row = new HashMap<String, Object>();
            row.put("value",value);
            row.put("isChecked",Boolean.valueOf(false));
            listData.add(row);
        }
    }

    public int selectedItemsSize(){
        int size = 0;
        for(HashMap<String,Object> row : listData){
            if((Boolean)row.get("isChecked")){
                size++;
            }
        }
        return size;
    }

    public ArrayList<String>  getSelected(){
        ArrayList<String> selected = new ArrayList<String>();
        for(HashMap<String,Object> row : listData){
            if((Boolean)row.get("isChecked")){
                selected.add(row.get("value").toString());
            }
        }
        return selected;
    }

    public void checkAll(){
        for(HashMap<String,Object> row : listData){
            row.put("isChecked",true);
        }
        notifyDataSetChanged();
    }
    public void uncheckAll(){
        for(HashMap<String,Object> row : listData){
            row.put("isChecked",false);
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            holder = new Holder();
            convertView = LayoutInflater.from(context).inflate(R.layout.list_row, null);
            holder.tv = (TextView)convertView.findViewById(R.id.listrowtext);
            holder.ckbox =(CheckBox)convertView.findViewById(R.id.listrowcheckBox);

            convertView.setTag(holder);
        }
        else{
            holder = (Holder) convertView.getTag();
        }


        holder.tv.setText(listData.get(position).get("value").toString());
        holder.ckbox.setChecked((Boolean) listData.get(position).get("value"));
        holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                listData.get(position).put("isChecked",isChecked);
                notifyDataSetChanged();
            }
        });


        return convertView;
    }


    static class Holder
    {
        TextView tv;
        CheckBox ckbox;
    }

}

答案 1 :(得分:0)

我会在ListAdapter中添加一个方法并迭代所有项目,检查视图是否为instance of CheckBox,然后再完成工作?

public ListAdapter ... {

    public void checkAll() {
        for (int position = 0; position < getCount(); position++) {
            final View view = getView(i);
            if (view instanceof CheckBox) {
                ((CheckBox) view).setChecked(true);
            }
        }
    }

}

如果我是mystaken,请显示R.layout.list_row布局文件。

答案 2 :(得分:0)

你是什么意思&#34;问题是它只显示所有选中的复选框并返回“检查了多少个框&#34; ?” / p>

您不必每次都要创建适配器的新实例,只需更新List中的检查状态并通知更改的数据,然后调用getView来更新listview