Check which checkbox is checked/Unchecked in android - android

I am creating checkboxes at runtime but i don't know how to find that which checkbox is checked and which is unchecked?This is the code.
for (String s : options)
{
chk = new CheckBox(this);
System.out.println(s);
chk.setId(i++);
chk.setText(s);
selected=s;
chk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked())
DisplayToast(selected);
else
DisplayToast(selected);
}
});
lm.addView(chk);
}

You can get the id of CheckBox using getId() method ..
CheckBox checkBox = ((CheckBox) v);
if (checkBox.isChecked())
{
int checkBoxId = checkBox.getId(); // It will give you checked checkbox id..
DisplayToast(selected);
}
else
DisplayToast(selected);
Update:
To get all CheckBox states you have to iterate thru ChildViews of lm layout.
Something like,
for (int i = 0; i < lm.getChildCount(); i++) {
View v = lm.getChildAt(i);
if (v instanceof CheckBox) {
if (((CheckBox) v).isChecked())
// Check Checkbox
else
// Unchecked Checkbox
}
}
Note: I would suggest you can use onCheckedChangeListener instead of View.OnClickListener() to check - uncheck event of CheckBox. (But it is optional, it also works with OnClickListener)

You should use onCheckedChangeListener to define whether your checkbox checked:
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//checked
} else {
//not checked
}
}
});

Related

How to get check box values from dynamically created checkbox

Here is the code for my check box.
if (type.equalsIgnoreCase("checkbox")){
String checkBoxText = dataObj.getString("checkboxname");
checkBox = dynamicviews.CreateCheckbox(context,value,checkBoxText);
id = R.id.gl + i + 9;
if (j == 2) {
j = 0;
tableRow = new TableRow(context);
tableRow.setPadding(0, 10, 0, 10);
tableLayout.addView(tableRow);
}
j++;
tableRow.addView(checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String string = checkBox.getText().toString();
Log.i("checkbox",string);
}
});
}
and below code is for creating checkbox
public CheckBox CreateCheckbox(Context context,String checkName,String checkBoxText){
checkBox = new CheckBox(context);
checkBox.setGravity(Gravity.CENTER);
checkBox.setTextAlignment(Gravity.CENTER);
checkBox.setText(checkBoxText);
checkBox.setTextColor(Color.WHITE);
checkBox.setBackgroundResource(R.drawable.custom_rdbtn);
checkBox.setButtonDrawable(new StateListDrawable());
checkBox.setCompoundDrawablePadding(10);
return checkBox;
}
and problem is am getting the value of last created checkbox for each one.
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String string = buttonView.getText().toString();
Log.i("checkbox",string);
}
});
i got the solution
You are adding the checkBoxobject to the tableRow BEFORE you set its setOnCheckedChangeListener - so it will only work for the last checkBox you've created.
To solve this, you simply need to do set the setOnCheckedChangeListener first, and then call the tableRow.addView(checkBox) - see the code below:
//first, set the setOnCheckedChangeListener on this checkBox,
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{ String string = buttonView.getText().toString();
Log.i("checkbox",string);
}
});
//only now do you add the view
tableRow.addView(checkBox);
Give it a try, I hope it helps.

Android incorrect behavior of child CheckBox

I have a custom ExpendableListViewAdapter. Like this:
Group
Child
Child
Child
Group
All his groups and childs have checkboxes.
I want parent CheckBox to dynamically check itself when all his children are checked.
How to implement this?
I've implemented selection of children then the parent element selected.
This is my method for it:
void selectGroup(boolean isSelected) {
for (Item itemChild : item.getItems()) {
if (isSelected) itemChild.isSelected = true;
else itemChild.isSelected = false;
itemChild.setSelected(isSelected);
}
notifyDataSetChanged();
}
And I summon it inside getGroupView:
holder.cbChild.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
item.isSelected = isChecked;
item.setSelected(isChecked);
if (getChildrenCount(groupPosition) != 0) {
selectGroup(item.isSelected);
}
}
});
And it works fine.
I've tried to implement parent selection as well.
Method:
public boolean isAllChildrenSelected(int groupPosition) {
int selectedNumber = 0;
for (int i = 0; i < getChildrenCount(groupPosition); i++) {
Item itemChild = getChild(groupPosition, i);
if (itemChild.isSelected) {
selectedNumber++;
}
}
if (selectedNumber == getChildrenCount(groupPosition)) {
notifyDataSetChanged();
return true;
} else return false;
}
And I summon this method inside my getGroupView as well:
if (getChildrenCount(groupPosition) != 0) {
if (isAllChildrenSelected(groupPosition)) {
holder.cbChild.setChecked(true);
}
}
And then, in getChildView inside setOnCheckedChangeListener for child CheckBox I summon notifyDataSetChanged();.
But I'm getting some strange behavior - for example, if group have 3 childs and I'm trying to select the 1st one, it selects the 2nd and the 3rd.
I think, this is because I putted notifyDataSetChanged(); in a wrong place, but I cannot figure out where exactly and how to fix it.
Well, it looks like I've figured it out.
Add this method:
private void selectGroupIfAllChildrenSelected() {
int numSelected = 0;
for (Child child: group.getChildrenList()) {
if (child.isSelected()) {
numSelected++;
}
if (group.getChildrenList().size() == numSelected) {
group.setSelected(true);
} else if (numSelected == 0) {
group.setSelected(false);
}
}
notifyDataSetChanged();
}
And summon it inside your getChildView method inside OnCheckedChangeListener:
holder.cbChild.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
child.setSelected(isChecked);
selectGroupIfAllChildrenSelected();
}
});
Also, don't forget to set to null your setOnCheckedChangeListener inside getChildView before you set a CheckBox state, otherwise you will get some strange behaviour:
holder.cbChild.setOnCheckedChangeListener(null);
holder.cbChild.setChecked(child.isSelected());
All this will also deselect your group CheckBox as soon as you deselect all the children.

How can I select only one Checkbox in a dynamic view

I have a screen that add dynamically a row with two textView and one CheckBox. My problem is that I only want that the user could check one, and the others have to be uncheck. If the user push another checkbox, enable this and disable all the other checkbox. I've test some things but I don't get the functionality that I want.
I can't change the configuration from checkbox to radioButton and I have to use the method that I'm using:
private selected_position = -1;
protected void addGreetingToListView(final GreetingListJson greetings) {
View row = inflater.inflate(R.layout.main_greetings_settings_row, greetingListView, false);
row.setTag(greetings);
playButton = (ToggleButton) row.findViewById(R.id.detail_play_greeting);
TextView greetingName = (TextView)row.findViewById(R.id.greetingTitle);
greetingName.setDuplicateParentStateEnabled(true);
TextView greetingDescription = (TextView)row.findViewById(R.id.greetingDescription);
greetingDescription.setDuplicateParentStateEnabled(true);
checkBox = (CheckBox) row.findViewById(R.id.checkBox_greeting_list);
checkBox.setTag(greetings);
checkBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view) {
if (((CheckBox) view).isChecked())
{
selected_position= greetingListView.getChildCount();
}
else
{
selected_position=-1;
}
}
});
greetingName.setText(greetings.Name);
greetingDescription.setText(greetings.Description);
row.setOnClickListener(this);
row.setOnLongClickListener(this);
row.setFocusable(true);
greetingListView.addView(row);
}
The XML of the Checkbox:
<CheckBox
android:id="#+id/checkBox_greeting_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
android:layout_centerVertical="true"/>
Firstly, declare an ArrayList in the class:
ArrayList<CheckBox> mCheckBoxes = new ArrayList<CheckBox>();
Then in addGreetingToListView add every new checkbox to mCheckBoxes and modify the click listener of the checkbox:
checkBox.setTag(greetings);
mCheckBoxes.add(checkBox);
checkBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view) {
if (((CheckBox) view).isChecked())
{
for (int i = 0; i < mCheckBoxes.size(); i++) {
if (mCheckBoxes.get(i) == view)
selected_position = i;
else
mCheckBoxes.get(i).setChecked(false);
}
}
else
{
selected_position=-1;
}
}
});

Setting checkbox dynamically from sqlite in a Fragment

I'm having trouble figuring out the best way to store and display checkboxes in a listview.
Right now I have the code in the getView method:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
//final ViewHolder holder;
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.grid_item, null);
}
ImageView img = (ImageView) convertView.findViewById(R.id.grid_item_img);
cb = (CheckBox) convertView.findViewById(R.id.chk_box_griditem);
if(photos.get(position).getIshidden()){
cb.setChecked(false);
}else{
cb.setChecked(true);
}
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
MySQLiteHelper db = MySQLiteHelper.getInstance(getActivity());
Log.d("checkbox", "status: " + photos.get(position).getIshidden());
if (isChecked) {
photos.get(position).setIshidden(true);
cb.setChecked(true);
Log.d("checkbox", "isChecked");
db.updatePhoto(photos.get(position));
} else {
photos.get(position).setIshidden(false);
cb.setChecked(false);
Log.d("checkbox", "isCheckedelse");
db.updatePhoto(photos.get(position));
}
}
});
imageLoader.displayImage(imgUrls[position], img, options, animateFirstListener);
//img.setImageResource(mImgRes);
return convertView;
}
The db helper takes a photo object as an argument and updates the row if it exists. So right now I update the current photo object isHidden() to be true or false then pass the updated object to db helper.
The physical database seems to be updating correctly. However a problem occurs when the checkboxes state is being set. The checkboxes seem to be randomly set as checked or unchecked.
Also I feel like doing this in the getView is cpu greedy but am not sure how else to do this.
First remove cb.setOnCheckedChangeListener...You do not need to set the OnCheckedChangeListener every time getView is called.you have already written the below code which will set check-box state(checked or unchecked) when list-view loads.
if(photos.get(position).getIshidden())
cb.setChecked(false);
else
cb.setChecked(true);
Now set onItemClick listener as below on list view :
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
MySQLiteHelper db = MySQLiteHelper.getInstance(getActivity());
Log.d("checkbox", "status: " + photos.get(position).getIshidden());
if(photos.get(position).getIshidden())
{
((CheckBox)arg0.getChildAt(position).findViewById(R.id.chk_box_griditem)).setChecked(true);
photos.get(position).setIshidden(false);
db.updatePhoto(photos.get(position));
}
else
{
((CheckBox)arg0.getChildAt(position).findViewById(R.id.chk_box_griditem)).setChecked(false);
photos.get(position).setIshidden(true);
db.updatePhoto(photos.get(position));
}
}
});
by that way you can check or uncheck the check-box and at the same time the check-box state(checked or unchecked) will be saved in your database.
I hope it will work.If not let me know..:)
When you are initializing your checkbox you set the Check state to false if the image is hidden.
if(photos.get(position).getIshidden()){
cb.setChecked(false);
}else{
cb.setChecked(true);
}
But in the Listener you set the image to hide when the checkbox is checked.
if (isChecked) {
photos.get(position).setIshidden(true);
...
This is actually the inverse. You are probably disturbed by that.
And you do not have to set the checked state again in the listener.
So your code in the listener could look like this:
if (isChecked) {
photos.get(position).setIshidden(false);
Log.d("checkbox", "isChecked");
db.updatePhoto(photos.get(position));
} else {
photos.get(position).setIshidden(true);
Log.d("checkbox", "isCheckedelse");
db.updatePhoto(photos.get(position));
}
1) Do not set the checkbox in the listener
2) Attach the listener in the checkbox only if convertView is null (i.e. when inflating). When you get your view from the convertview it has its listener set already.
Change and then log. OnCheckedChange you can get away with no if statements and just use the boolean. You don't need to set the value in of the check box in the checkedchanged listener. Intialize db in onResume so it's available no telling how many times a user will click something and the db initialization will slow things down.
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
photos.get(position).setIshidden(isChecked);
db.updatePhoto(photos.get(position));
Log.d("checkbox", isChecked.toString());
}
});
#Override
protected void onResume() {
if (db==null) {
db = MySQLiteHelper.getInstance(getActivity());
}
}

how to add and remove the selected checkbox id to and from arraylist in android?

I am storing the selected checkbox value into arraylist when it is selected by the user and removing from the same arraylist when unchecked by the user. But I am having one problem with this. i.e for example I selected the checkboxes 0,1,4,6. Then I unchecked 0th checkbox. But from the arraylist 6 is removed. Next time I unchecked 1th position checkbox. But this time in from the arraylist nothing is deleted. Finally I unchecked 0 and 4 but still nothing is deleted from arraylist. The values 0,1,4 are still existing in the arraylist. How to overcome this issue?
I want to store the selected items and remove the unselected items. Please help me regarding this....
My Code:
public static ArrayList<String> selchkboxlist = new ArrayList<String>();;
String chk;
cbs = new CheckBox[20];
for(k=0; k<List.size(); k++)
{
arr = List.get(k);
cbs[k] = new CheckBox(getContext());
Rl.addView(cbs[k]);
cbs[k].setText((CharSequence) arr.get(2));
cbs[k].setTextColor(Color.parseColor("#000000"));
cbs[k].setId(k);
cbs[k].setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cbs = (CheckBox) v ;
if (((CheckBox) v).isChecked()) {
chk = Integer.toString(v.getId());
selchkboxlist.add(chk);
Toast.makeText(Myclass.this, "Selected CheckBox ID" + v.getId(), Toast.LENGTH_SHORT).show();
System.out.println("selected checkboxes"+selchkboxlist);
}
else
{
selchkboxlist.remove(chk);
Toast.makeText(Myclass.this, "Not selected", Toast.LENGTH_SHORT).show();
System.out.println("un selected checkboxes"+selchkboxlist);
}
}
});
}
Will be thankful....
In line 4... i guess you should have list size for selchkboxlist .
create a class like this
public class checkboxList
{
private boolean Checked;
public checkboxList( boolean Checked) {
super();
this.Checked = Checked;
}
public void setChecked(boolean state)
{
this.Checked = state;
}
public boolean getChecked()
{
return Checked;
}
}
Then in onclick method you
if (checkBox.isChecked() == true) {
checkboxList.get(position).setChecked(true);
}
else {
checkboxList.get(position).setChecked(false);
}

Categories

Resources