ListView with Checkboxes Android

[亡魂溺海] 提交于 2019-12-05 08:00:49

问题


The Activity below, ContactMailAdapter.class is my list view adapter containing checkbox. If i want to get the position of a row that has been checked. how can this be done. I have several checkboxes in my list and I can checked multiple checkbox. My logic is that I should store each position that has been checked. then call the data from my arraylist but for now I am not able to get the position of a checked item from my adapter.

public class ContactMailAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<Destinataire> data;
    private static LayoutInflater inflater = null;

    ViewHolder holder;
    static String src;

    PopMessage main;

    public ContactMailAdapter(Activity a, ArrayList<Destinataire> mArticles) {

        activity = a;
        data = mArticles;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }



    public ContactMailAdapter (PopMessage m){
                this.main=m;
    }


    @Override
    public int getCount() {
        return data.toArray().length;

    }

    @Override
    public Object getItem(int position) {

        return position;
    }

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

    public static class ViewHolder {

        public TextView one;
        public TextView two;
        public CheckBox check;

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi = convertView;

        if (convertView == null) {

            vi = inflater.inflate(R.layout.popise_item, null);
            holder = new ViewHolder();
            holder.one = (TextView) vi.findViewById(R.id.title_top);
            holder.two = (TextView) vi.findViewById(R.id.title_bottom);
            holder.check = (CheckBox)vi.findViewById(R.id.search_imag);
            vi.setTag(holder);

        } else
            holder = (ViewHolder) vi.getTag();


            holder.one.setText(data.get(position).getName());
            holder.two.setText(data.get(position).getEmail());




            vi.findViewById(R.id.search_imag).setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    if (holder.check.isChecked())
                        System.out.println("false"+v.getId());
                    else 
                        System.out.println("false");

                }
            });


            holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()                  
                     {
                      @Override
                      public void onCheckedChanged(CompoundButton buttonView,
                              boolean isChecked) {



                      }
                  });



        /*  vi.findViewById(R.id.search_image).setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    v.findViewById(R.id.search_image).setBackgroundResource(R.drawable.boutton_off);
                    if (holder.check.isChecked())
                        System.out.println("true");
                    else 
                        System.out.println("false");

                }
            }); */



        return vi;
    }


}

NEW UPDATE

ids = new ArrayList<String>();
            if (ids.contains(holder.check.getId() + "")) {
                        holder.check.setChecked(true);
                    } else {
                        holder.check.setChecked(false);
                    }

                    holder.check
                            .setOnCheckedChangeListener(new OnCheckedChangeListener() {



                                public void onCheckedChanged(CompoundButton buttonView,
                                        boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    int id = buttonView.getId(); 
                                    if (isChecked) {
                                        if (ids.contains(id + "")) {
                                        } else {
                                            ids.add(id + "");
                                            id++;
                                            System.out.println( "receipe" + id);

                                        }
                                    } else {
                                        if (ids.contains(id + "")) {
                                            ids.remove(id + "");
                                            System.out.println( "receipe" + id);

                                          //  ids--;
                                        } else {
//                                        id = 0;
                                        }

                                    }

                                }
                            });

回答1:


Have a look at this sample this will provide you the perfect solution i have used it to get the selected position in my project. it worked like a charm with the concept of

checkbox.settag and gettag() methods. hope this will help you . 

http://amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html




回答2:


This is how i implemented the same, but i used images instead of built-in checkboxes to check/uncheck the list item.

My listview's single row contains TextView and Imageview.

Below is the code of ArrayAdapter and listview's onItemClick() event:

static class Category {

        String cat_name = "";
        int cat_id = 0;
        Boolean checked = false;

        Category(int cat_id, String name) {
            this.cat_name = name;
            this.cat_id = cat_id;
        }

        public int getId() {
            return cat_id;
        }

        public String getCatName() {
            return cat_name;
        }

        public Boolean getChecked() {
            return checked;
        }

        public void setChecked(Boolean checked) {
            this.checked = checked;
        }

        public boolean isChecked() {
            return checked;
        }

        public void toggleChecked() {
            checked = !checked;
        }
    }

    static class CategoryViewHolder {

        ImageView imageViewCheck;
        TextView textViewCategoryName;

        public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
            imageViewCheck = iv_check;
            textViewCategoryName = tv_category_name;
        }

        public ImageView getImageViewCheck() {
            return imageViewCheck;
        }

        public TextView getTextViewCategoryName() {
            return textViewCategoryName;
        }
    }

    static class CategoryArrayAdapter extends ArrayAdapter<Category> {

        LayoutInflater inflater;

        public CategoryArrayAdapter(Context context, List<Category> categoryList) {

            super(context, R.layout.single_row_delete_data,
                    R.id.textViewSingleRowDeleteData, categoryList);
            inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Category category = (Category) this.getItem(position);

            final ImageView imageViewCheck;
            final TextView textViewCN;

            if (convertView == null) {

                convertView = inflater.inflate(R.layout.single_row_delete_data,
                        null);

                imageViewCheck = (ImageView) convertView
                        .findViewById(R.id.imageViewSingleRowDeleteData);
                textViewCN = (TextView) convertView
                        .findViewById(R.id.textViewSingleRowDeleteData);

                convertView.setTag(new CategoryViewHolder(imageViewCheck,
                        textViewCN));
            }

            else {

                CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
                        .getTag();
                imageViewCheck = viewHolder.getImageViewCheck();
                textViewCN = viewHolder.getTextViewCategoryName();
            }

            imageViewCheck.setFocusable(false);
            imageViewCheck.setFocusableInTouchMode(false);
            imageViewCheck.setClickable(true);
            imageViewCheck.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    ImageView iv = (ImageView) v;
                    Category category = (Category) iv.getTag();

                    if (category.getChecked() == false) {
                        imageViewCheck.setImageResource(R.drawable.set_check);
                        listOfItemsToDelete.add(category.getId());
                        category.setChecked(true);
                    } else {
                        imageViewCheck
                                .setImageResource(R.drawable.set_basecircle);
                        listOfItemsToDelete.remove((Integer) category.getId());
                        category.setChecked(false);
                    }
                }
            });
            imageViewCheck.setTag(category);

            if (category.getChecked() == true)
                imageViewCheck.setImageResource(R.drawable.set_check);
            else
                imageViewCheck.setImageResource(R.drawable.set_basecircle);

            textViewCN.setText(category.getCatName());

            return convertView;
        }
    }

ListView's onItemClick() event:

lv_delete_data.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                ImageView imageView = (ImageView) arg1
                        .findViewById(R.id.imageViewSingleRowDeleteData);
                Category category = (Category) imageView.getTag();

                if (category.getChecked() == false) {
                    imageView.setImageResource(R.drawable.set_check);
                    listOfItemsToDelete.add(category.getId());
                    category.setChecked(true);
                } else {
                    imageView.setImageResource(R.drawable.set_basecircle);
                    listOfItemsToDelete.remove((Integer) category.getId());
                    category.setChecked(false);
                }
            }
        });

This is how i implemented, the same thing which you require. If you have any query you can ask me.




回答3:


You will have to play around setTag() and getTag(). I would like to recommend you reading these posts:

Android: Change image for a particular item in listview and Getting an issue while checking the dynamically generated checkbox through list view.




回答4:


Take a look here. This tutorial covers how to add checkboxes to listViews and handle updating and checking their status




回答5:


You can try this...

List<String> ids = new ArrayList<String>();
holder.check_favourite.setId(position);


        if (ids.contains(holder.check_favourite.getId() + "")) {
            holder.check_favourite.setChecked(true);
        } else {
            holder.check_favourite.setChecked(false);
        }
        int id= 0;

        holder.check_favourite
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        // TODO Auto-generated method stub
                        int check = buttonView.getId();
                        if (isChecked) {
                            if (ids.contains(check + "")) {
                            } else {
                                ids.add(check+ "");
                                id++;
                            }
                        } else {
                            if (ids.contains(check + "")) {
                                ids.remove(check + "");
                                id--;
                            } else {

                            }

                        }

                    }
                });

The if condition to set checkbox true or false is used so that your checkbox doesn't get unchecked when you scroll your listview... This is my code apply the same code for your checkbox..Hope you get it...




回答6:


If your intention is to get or store checked item, you can use array adapter. Check out this code.It might help you out.

/Defining checkbox click event listener/

OnClickListener clickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {

        CheckBox chk = (CheckBox) v;

        int itemCount = getListView().getCount();

        for(int i=0 ; i < itemCount ; i++){

            getListView().setItemChecked(i, chk.isChecked());
        }
    }

};

/**Defining click event listener for the listitem checkbox**/

OnItemClickListener itemClickListener = new OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    CheckBox chk = (CheckBox) findViewById(R.id.chkAll);

    int checkedItemCount = getCheckedItemCount();

    if(getListView().getCount()==checkedItemCount)

        chk.setChecked(true);

    else

        chk.setChecked(false);
    }
};

/**Getting reference to checkbox available in the main.xml layout**/

CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);

/**Setting a click listener for the checkbox**/

chkAll.setOnClickListener(clickListener);

/**Setting a click listener for the listitem checkbox**/

 ` getListView().setOnItemClickListener(itemClickListener); `

}

/Returns the number of checked items/

private int getCheckedItemCount() {

int cnt = 0;

SparseBooleanArray positions = getListView().getCheckedItemPositions();

int itemCount = getListView().getCount();

for(int i=0;i<itemCount;i++){

    if(positions.get(i))

        cnt++;
}

return cnt;

}

And to update the checked item , use

SparseBooleanArray checked = getListView().getCheckedItemPositions();



来源:https://stackoverflow.com/questions/16355923/listview-with-checkboxes-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!