Check and Uncheck All CheckBoxes in ListView - android

I was surprised that I couldn't find an existing answer on Stack that I could use for this, so here I am.
I have a ListFragment with a list attached to a SimpleCursorAdapter comprised of the rows defined by the following row.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/story_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/story"
android:layout_width="wrap_content"
android:layout_height="24sp"
android:lines="1"
android:scrollHorizontally="true"
android:singleLine="true"
android:layout_alignBaseline="#+id/story_check_box"
android:layout_alignBottom="#+id/story_check_box"
android:layout_toRightOf="#+id/story_check_box" />
</RelativeLayout>
I connect the list with the adapter with the following code in my ListFragment:
adapter = new SimpleCursorAdapter(getActivity(), R.layout.row, null, new String[] { CProvider.Stories.TITLE }, new int[] { R.id.story }, 0);
setListAdapter(adapter);
I then try to use a CheckBox in my fragment to toggle all the list checkboxes as follows:
CheckBox selectAll = (CheckBox) rootView.findViewById(R.id.select_check_box);
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ListView listView = getListView();
for(int i=0; i < getListAdapter().getCount(); i++){
View view = getViewByPosition(i, listView);
CheckBox cb = (CheckBox)view.findViewById(R.id.story_check_box);
if (isChecked) {
cb.setChecked(true);
}
else {
cb.setChecked(false);
}
}
}
});
I got getViewByPositionfrom here: Get ListView children that are not in view, and that almost works, but a few of the checkboxes don't get checked (and there is a pattern to it, but I can't seem to figure it out). It also seems a bit kludgier than I would think is necessary.
I want the checkboxes on the left, so I don't want to use checkedtextviews. Maybe I need to extend CursorAdapter and override getView?
Thanks in advance.

Maybe I'm not correctly understanding your question but what I understood was that you wanted to check and uncheck all the checkboxes thanks to one "Select All checkbox".
Then, what I would do is to put the state of the "select all checkbox" as a variable of the class (as a boolean) which is overwritten by your selectAll.setOnCheckedChangeListener and say to the adapter "Hey, my state changed!" every time the checkbox changed its state.
Something like this:
class Dummy{
boolean isAllSelected = false;
Checkbox selectAll = (find or create your CheckBox)
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) isAllSelected = true;
else isAllSelected = false;
listView.getAdapter().notifyDataSetChanged();
}
}
And then, you just have to override the getView() of this adapter (like you suggested) adding a "if (isAllSlected)" condition.
To me, it sounds the easiest to do but it's maybe not that good to call the notifyDataSetChanged() method every time the user clicks on a checkbox (it's not that efficient for so minor changes). Anyway, hope it helps (the code I wrote is maybe not with the correct syntax: I wrote it directly on the website form)!

Below is what I wound up doing. In addition to taking care of the "select all/ unselect all" functionality, it handles checking/unchecking a checkbox when the text of a list item is selected/unselected, and vice versa. I was concerned about getView being called frequently, but setItemChecked causes getView to be called no matter what, so there's a limit to how much calls to getView can be avoided. As ataulm mentioned in a comment, maybe a composite view would a solution with less fuss.
In onCreateView:
selectAllCheckBox = (CheckBox) rootView.findViewById(R.id.select_all_check_box);
selectAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ListView listView = getListView();
for(int i=0; i < getListAdapter().getCount(); i++){
listView.setItemChecked(i, isChecked);
}
}
});
I also created a custom SimpleCursorAdapter with the following code, which also uses a simple ViewHolder class. In getView I check which items in the list are selected and check the checkboxes corresponding to those items. There's also code that sets a list item as selected or not if its corresponding checkbox has been clicked (i.e., checked or unchecked).
class AvailableCursorAdapter extends SimpleCursorAdapter {
AvailableCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
ViewHolder holder = (ViewHolder)row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
holder.storyCheckBox.setChecked(false);
holder.story.setTextColor(Color.LTGRAY);
long [] checkedIds = getListView().getCheckedItemIds();
if (checkedIds != null) {
for (int i = 0; i < checkedIds.length; i++) {
if (checkedIds[i] == getListAdapter().getItemId(position)) {
holder.storyCheckBox.setChecked(true);
holder.story.setTextColor(Color.WHITE);
break;
}
}
}
final boolean isChecked = holder.storyCheckBox.isChecked();
holder.storyCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getListView().setItemChecked(position, !isChecked);
}
});
return(row);
}
}
.
class ViewHolder {
CheckBox storyCheckBox;
TextView story = null;
ViewHolder(final View row) {
storyCheckBox = (CheckBox) row.findViewById(R.id.story_check_box);
story = (TextView) row.findViewById(R.id.story);
}
}
Finally, the following code causes getView to be called when a single ListItem is clicked, so that its corresponding checkbox gets selected or unselected, as appropriate:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ViewHolder holder = (ViewHolder) v.getTag();
holder.storyCheckBox.setChecked(false);
holder.story.setTextColor(Color.LTGRAY);
long [] checkedIds = l.getCheckedItemIds();
if (checkedIds != null) {
for (int i = 0; i < checkedIds.length; i++) {
if (checkedIds[i] == getListAdapter().getItemId(position)) {
holder.storyCheckBox.setChecked(true);
holder.story.setTextColor(Color.WHITE);
break;
}
}
}
}

Related

Checked checkbox outside the adapter class on listView

In my Activity i have a list view and a check box.I created an adapter and do all stuff about it.In adapter i have 4 checkbox that loaded into list view.
I want to when user check this man checkBox in activity all checkBoxs on adapter is checked so in order to In activity first i find check box and finally i override setOnCheckedChangeListener method.
To find out number of view in adapter i am using TmpAdp.getCount().TmpAdp is my instance adapter.
This is a completed code :
chb_allCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
for (int i = 0; i < TmpAdp.getCount(); i++) {
View view = Glist.getChildAt(i);
CheckBox ch_item = view.findViewWithTag(i);
// CheckBox ch_item = view.findViewById(R.id.chb_send_info); // this is not work like findViewWithTag
ch_item.setChecked(true);
}
TmpAdp.checkAll(TmpAdp.getCount());
TmpAdp.notifyDataSetChanged();
} else {
}
}
});
The problem is, when i checked mani check box (chb_allCheck), none of them of check boxs inside adapter is not checked ?
This is a part of adapter class and getView method:
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) Tmpcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.liststyle_saveed, parent, false);
BtnChangeToInPross = rowView.findViewById(R.id.BtnChangeToInPross);
TextView txtNosaziCodestr = rowView.findViewById(R.id.NosaziCodestr);
checkBox = rowView.findViewById(R.id.chb_send_info);
checkBox.setTag(position);
As you can see when i have clicked on Main check boxs, none of them of check box inside adapter is not checked
First of all make a Model class. In which you will take boolean isChecked.
Now in adapter class you will attach that model boolean to the list item checkbox.
checkbox.setChecked(model.isChecked());
When you check your main checkbox. Then just change isChecked boolean in your model list.
boolean isChecked = mainCheckBox.isChecked();
for(Model model : adapter.getList()){
model.setChecked(isChecked);
}
adapter.notifyDataSetChanged();
Here when you change checked status of model and notify your list. Then all your checkBox will be checked automatically, because these are attached to the model checked field.
It is logic, I did not write full code, you will make Model class, and will attach model by your list item.
Create a model class and make getter and setter method for check and uncheck Checkbox
Click of Main Checkbox in Activity
chb_allCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean
for (int i = 0; i < yourList.size; i++) {
if(checked){
yourlist.get(i).setCheckBoxAdapter(true);
}
else{
yourlist.get(i).setCheckBoxAdapter(false);
}
}
TmpAdp.notifyDataSetChanged();
}
});
in yourAdapterClass
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
CheckBoxModelClass modelclass= getItem(position);
if(modelclass.getCheckbox()){
adapterCheckBox.setChecked(true);
}
else{
adapterCheckBox.setChecked(false);
}
return convertView;
}
Tank you of your guys, You have made good suggestions but let me complete my way.
My problem was TmpAdp.notifyDataSetChanged();.When i removed this, code work completally.
I have completed my code and works perfectly and it can be an additional way to Select
all checkbox.
chb_allCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
for (int i = 0; i < TmpAdp.getCount(); i++) {
View view = Glist.getChildAt(i);
CheckBox ch_item = view.findViewById(R.id.chb_send_info);
ch_item.setChecked(true);
}
TmpAdp.checkAll(TmpAdp.getCount());
} else {
for (int i = 0; i < TmpAdp.getCount(); i++) {
View view = Glist.getChildAt(i);
CheckBox ch_item = view.findViewById(R.id.chb_send_info);
ch_item.setChecked(false);
}
TmpAdp.removeAll();
}
}
});

CheckBox event listener from setChoiceMode(ListView.CHOICE_MODE_MULTIPLE)

So I have a listview that I want to add checkboxes to.
lv = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
lv.setAdapter(adapter);
lv.setItemsCanFocus(true);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
This works and the checkboxes show up. Then I have my setOnItemClickListener() for my listview because the user needs to select an item, then the next acitivty will be launched
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
Intent components = new Intent();
components.setClass(context, ComponentsActivity.class);
components.putExtra("studyID", studyID);
components.putExtra("studyName", studyName);
startActivity(components);
}
});
However, I want to add a checkbox so that the user can tick that item in the listview to perform other actions. The problem is I can't differentiate the events. When I click on the checkbox, it gets checked but then the list item also gets selected and the new activity starts. I only want the checkbox to be affected when they click on it, not have it launch the new acitivty. I know you can also just create your own adapter but why bother if I can make a checkbox in 2 lines of code. Any suggestions? I just want to be able to check the textbox and get the id of the checked items.
I never managed to find anything for what I was looking for so I bit the bullet and decided to learn how to make my own custom adapter class. Here is my code if anybody ever runs into this problem. This adapter class is for a listview with text(TextView) and a checkbox.
public class CustomAdapter extends BaseAdapter
{
ArrayList<String> studies;
Context context;
LayoutInflater myInflater;
ArrayList<Boolean> positionArray;
public CustomAdapter(ArrayList<String> arr, Context c)
{
studies = arr;
context = c;
myInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
positionArray = new ArrayList<Boolean>();
for(int i = 0; i < studies.size(); ++i)
{
positionArray.add(false);
}
}
#Override
public int getCount() {
return studies.size();
}
#Override
public Object getItem(int i) {
return studies.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void remove(int i)
{
this.studies.remove(i);
this.positionArray.remove(i);
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
final int pos = position;
Holder holder = null;
//Create the views and populate it with an element from teh array
if(view == null)
view = myInflater.inflate(R.layout.custom_list_layout, viewGroup, false);//made my own layout for each listview 'cell'
holder = new Holder();
TextView study = (TextView)view.findViewById(R.id.adapterTextView);
holder.ckbox = (CheckBox)view.findViewById(R.id.adapterCheckBox);
holder.ckbox.setOnCheckedChangeListener(null);
study.setText(studies.get(position));
holder.ckbox.setFocusable(false);
//Since this method gets called whenever we scroll(view recycling), we have to re-check the checkboxes
holder.ckbox.setChecked(positionArray.get(position));
holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
//checkBoxArray[pos].setChecked(isChecked);
positionArray.set(pos, isChecked);
}
});
return view;
}
static class Holder
{
CheckBox ckbox;
}
}

how to bind a checkbox to a listview

I have a listview containing on each row a textview with a checkbox, so when the checkbox is checked and we scroll down through the listview the checkbox instance will be taken from a place to another (reused..) and I have several checked checkboxes how to fix that I tried to bind the checkbox to the listview but that didn't work my code is:
SimpleCursorAdapter adapter =new SimpleCursorAdapter(this,R.layout.rating,cu,new String[]{"Title","Favorites"}, new int[]{R.id.text1,R.id.bt_rating},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listv.setAdapter(adapter);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
/** Binds the Cursor column defined by the specified index to the specified view */
public boolean setViewValue(View view, Cursor cursor, int columnIndex){
if(view.getId() == R.id.bt_rating){
((CheckBox)view).setChecked(Boolean.valueOf(cursor.getString(cursor.getColumnIndex("Favorites"))));
((CheckBox)view).setOnCheckedChangeListener(myCheckChangList);
return true; //true because the data was bound to the view
}
return false;
}
});
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
buttonView.setChecked(isChecked);
}
};
My xml code of the content of the row of my listview is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/bt_rating"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:button="#android:drawable/btn_star"/>
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/fsinlistview"
/>
</LinearLayout>
It looks like your OnCheckedChangedListener is the problem here. If you look at your code, see that every checkbox is getting a reference to the same listener. So when you check one box, you're setting every other box as checked too - and you're not updating your backing data, either.
Your OnCheckedChangedListener should not be updating the view state of the checkbox - the callback is fired because the state has already changed.
So you need to do the following steps when a user checks the checkbox:
Figure out which item was checked, and how that corresponds to your data
Update your data to suit the new checked/unchecked state
Notify your adapter of a data change/update your cursor
You could do this something like the following, tagging the view with the ID of the row it represents:
public boolean setViewValue(View view, Cursor cursor, int columnIndex){
if(view.getId() == R.id.bt_rating){
view.setTag(cursor.getInt(cursor.getColumnIndex(SomeDBContract.ID)));
((CheckBox)view).setChecked(Boolean.valueOf(cursor.getString(cursor.getColumnIndex("Favorites"))));
((CheckBox)view).setOnCheckedChangeListener(myCheckChangList);
return true; //true because the data was bound to the view
}
return false;
}
Then, in your listener you can update your database according to that ID:
CheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int rowId = (int) buttonView.getTag();
// Handle updating the database as per normal
updateSomeDbRowAsChecked(rowId, isChecked);
}
};
Finally, you'll need to update your cursor adapter with a new cursor once the database row is updated:
myAdapter.swapCursor(newCursor);
You'll have to adjust all of this to suit your code, but it should give you an idea of one way you can approach this problem.
In any Listview, the view are reused. As you scroll through the list, those that scroll up and off screen are recycled and used with newer information as it comes in below.
You need to keep track of your checkboxes with a sparse array. Mark the index in the array as cherked/unchecked as the user touches each. You then set the state of the checkbox based on the value in the array.
Here is some example code from an an older app, that does both a "select all" checkboxes as well as manages the entire list of those checked and unchecked. It was for a classroom attendance app I wrote, so it was much easier for a teacher to select "ALL" being in class and then unselect those that weren't present.
I have two checkboxes in this listview, and two sparse arrays, itemCheckedHere and itemCheckedLate (whether a student is in class, or was late).
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private Long classnum;
private gradeBookDbAdapter mDbHelper;
public static final int LATE=2;
public static final int ATTEND=1;
int idxCol;
int idx;
// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, Long mRowId) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
mDbHelper = new gradeBookDbAdapter(context);
mDbHelper.open();
classnum = mRowId;
c.moveToFirst();
}
public class ViewHolder{
public TextView text;
public TextView text2;
public ImageView image;
public CheckBox here;
public CheckBox late;
}
public View getView(final int pos, View inView, ViewGroup parent) {
Bitmap bm;
ImageView studentPhoto;
View vi=inView;
final ViewHolder holder;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.show_attendance, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.stuname);
holder.text2=(TextView)vi.findViewById(R.id.stuIndex);
holder.image=(ImageView)vi.findViewById(R.id.icon);
holder.here=(CheckBox)vi.findViewById(R.id.attend);
holder.late=(CheckBox)vi.findViewById(R.id.late);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
c.moveToPosition(pos);
int index = c.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
String name = c.getString(index);
holder.text.setText(name);
index = c.getColumnIndex(gradeBookDbAdapter.KEY_ROWID);
String Index = c.getString(index);
holder.text2.setText(Index);
bm = gradeBookDbAdapter.getStudentPhoto(name);
if (bm != null) {
holder.image.setImageBitmap(bm);
}
else {
// use icon image
holder.image.setImageResource(R.drawable.person_icon);
}
// pull out existing attend/late fields and set accordingly
int attend = c.getInt(c.getColumnIndex(gradeBookDbAdapter.KEY_ATTEND));
if(attend==1){
holder.here.setChecked(true);
itemCheckedHere.set(pos, true);
}
//else {
// holder.here.setChecked(false);
// itemCheckedHere.set(pos, false);
//}
int late = c.getInt(c.getColumnIndex(gradeBookDbAdapter.KEY_LATE));
if (late==1){
holder.late.setChecked(true);
itemCheckedLate.set(pos, true);
}
//else {
// holder.late.setChecked(false);
// itemCheckedLate.set(pos, false);
//}
if (selectAllTouched) {
if(selectAll){
holder.here.setChecked(true);
itemCheckedHere.set(pos, true);
int who= new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 1, attendDate );
}
else{
holder.here.setChecked(false);
itemCheckedHere.set(pos, false);
int who = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 0, attendDate );
}
}
holder.here.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.attend);
if (cb.isChecked()) {
itemCheckedHere.set(pos, true);
int Index = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(Index, classnum, ATTEND, 1, attendDate );
} else if (!cb.isChecked()) {
itemCheckedHere.set(pos, false);
int Index = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(Index, classnum, ATTEND, 0, attendDate );
}
}
});
holder.late.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.late);
if (cb.isChecked()) {
itemCheckedLate.set(pos, true);
int Index = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(Index, classnum, LATE, 1, attendDate );
} else if (!cb.isChecked()) {
itemCheckedLate.set(pos, false);
int Index = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(Index, classnum, LATE, 0, attendDate );
}
}
});
holder.here.setChecked(itemCheckedHere.get(pos)); // this will Check or Uncheck the
holder.late.setChecked(itemCheckedLate.get(pos)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return vi;
}
}
}

Custom list View with edit text and check boxes

I'm new to programming and having problem with using getCheckedItemPositions() for check boxes and getting edit values from edit text in custom list view. Can anyone help me with an example to create custom list view which has above functionality. Thanks.
*this is custom listview xml code
<CheckBox android:id="#+id/checkBox" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="CheckBox"
android:onClick="clickHandler"
></CheckBox>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="TextView"
android:id="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true" android:layout_marginBottom="14dp"
android:layout_toLeftOf="#+id/checkBox">
*This is code for set up listview
lv1 = (ListView)dialog.findViewById(R.id.l1);
adapter2 = new SimpleCursorAdapter(
this,
R.layout.custom,
cursor2,
new String[] {"ItemName"},
new int[] {R.id.textView1});
lv1.setItemsCanFocus(false);
lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv1.setAdapter(adapter2);
*this what I tried to do when checked
public void onClick(View v) {
int len = lv1.getCount();
SparseBooleanArray checked = lv1.getCheckedItemPositions();
for (int i = 0 ; i < len; i++)
if (checked.get(i)) {
String item = mArrayList.get(i);
mItems.add(mArrayList.get(i));
System.out.println(item);
/* do whatever you want with the checked item */
}
But this is not working. And also I want to use edit text in this manner for getting values.when I checked and click the button app terminate.
The following code will solve your problem.
public class SimpleCursorAdapter extends ArrayAdapter {
private Context mcontext;
private View rowview;
LayoutInflater inflater;
public static ArrayList<Boolean > itemchecked=new ArrayList<Boolean>();
public SimpleCursorAdapter(Context context,ArrayList<String> mylist)
{
super(context,your layout id);
mcontext=context;
//this is the important step
for (int i = 0; i < this.getCount(); i++)
{
itemchecked.add(i,false); // initializes all items value with false
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
rowview=convertView;
if(convertView==null)
{
rowview = inflater.inflate(R.yourlayout, parent, false);
}
TextView textView_heading = (TextView) rowview.findViewById(R.id.textView1);
CheckBox checkbox_detail=(CheckBox) rowview.findViewById(R.id.checkBox1);
checkbox_detail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
if (cb.isChecked()) {
itemchecked.set(position, true);
// do some operations here
} else if (!cb.isChecked()) {
itemchecked.set(position, false);
// do some operations here
}
}
});
checkbox_detail.setChecked(itemchecked.get(position));
textView_heading.setText(userheading_list.get(position));
return rowview;
}
}
//now the custom list part finish
Now, to get all the information from list and also watch which checkbox is checked:
for(int i=0;i<yourlistadapterobject.getCount();i++)
{
View content_view=msg_adapter.getView(i,null , user_detail_list);
System.out.println("the list count"+user_detail_list.getCount());
if(MyContactAdapter.itemchecked.get(i))
{
System.out.println("is checked true");
TextView tv_heading= (TextView) content_view.findViewById(R.id.textView1);
String text=tv_heading.getText();
}
}
By doing this, you can get all the information against checkbox which is checked.

Targeting specific checkbox with tag in listview

In my app I have a list with rows, each containing an image, text, and a checkbox. I overrode the getView method of my simpleadapter to include a tag for each checkbox based on its position in the row (code is here http://www.heypasteit.com/clip/YME ... bs and bs1 are booleans). That way I could tell which checkbox was being changed when onCheckedChanged was invoked. However, I need to set the state of individual checkboxes manually. For example, set the state of the checkbox with tag "3" (the checkbox on row 3) to "true."
Any help on this would be much appreciated!
You can replace your approach with an array of booleans. For example, if you have 15 elements in array, you can create a boolean[15], and change state of different positions when user clicks a checkbox, as well as set the initial state in the beginning.
Not a perfect example, but I hope you'll get the idea:
public class YourActivity extends Activity {
protected boolean[] checkStates;
protected void onCreate(android.os.Bundle savedInstanceState) {
//... Some of your code where you get a list of you objects
checkStates = new boolean[list.size()];
// As an example, let's check some of them:
checkStates[3] = true;
checkStates[7] = true;
//.. Something more
};
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.rowsecond, new String[] {"icon", "name"}, new int[] {R.id.image1, R.id.text1}) {
public View getView(int position, View convertView, ViewGroup parent) {
final View v = super.getView(position, convertView, parent);
boxer = (CheckBox)v.findViewById(R.id.checkbox);
boxer.setTag(position);
boxer.setOnCheckedChangeListener(checkedChangeListener);
boxer.setChecked(checkStates[position]);
return v;
}
private final OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
final Integer position = (Integer) buttonView.getTag();
checkStates[position] = isChecked;
}
};
};
}
Don't forget to call yourAdapterInstance.notifyDataSetChanged() if you are trying to update checkboxes states from outside of checkedChangeListener and after initial onCreate() method;

Categories

Resources