How to get CheckBox value present in RadioGoup in Android? - android

New to Android,
I am creating a question Answer App. So I want to get the value of checkBoxes.
I know how to get value of radio button present in Radio Group.
But I want to know is it good practice to keep checkBixes in RadioGroup and how to get the Checkboxes value?

What do you mean by getting CheckBox value? You can get the state (checked or not checked) and you can also get the text label for the CheckBox itself (getText()).
As for keeping them in a RadioGroup, it will depend largely on your use case (when grouped, the user might expect that only one CheckBox at the time can be checked). If you were to implement RadioGroup, you will have to implement a listener and then determine which CheckBox was checked. For that you can look at the accepted answer on this closely related question here.
Here is how you can get the Text of the CheckBox that was checked/unchecked:
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
CheckBox checkBox = (CheckBox)findViewById(checkedId);
//here you can check if it was checked or not, including the text
String text = checkBox.getText().toString();
boolean isChecked = checkBox.isChecked();
}
I hope this sheds some light.

Unfortunately as you would expect to utilize radioGroup's getCheckedRadioButtonId() for radio buttons, there is no such thing for check boxes. There are many ways to do this but I think the simplest and cleanest way would be the following:
For CheckBoxes
// Define one listener to use it for all of your CheckBoxes:
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// You can also use the buttonView.isChecked() instead of isChecked parameter too : if(ButtonView.isChecked)..
if(isChecked) {
// Do stuff with this checkBox for example:
String stringToShow = buttonView.getText();
}
}
};
// Reference your CheckBoxes to your xml layout:
CheckBox checkBox1 = findViewById(R.id.checkBox1);
CheckBox checkBox2 = findViewById(R.id.checkBox2);
// and many more check boxes..
/* Set the above listener to your Check boxes so they would
notify your above piece of code in case their checked status
changed:*/
checkBox1.setOnCheckedChangeListener(listener);
checkBox2.setOnCheckedChangeListener(listener);
// and many more check boxes..

Related

Editable List with checkbox

I want to create a editable list with checkboxes for creating todo (just like checkboxes in Google Keep). Is there a control to achieve this ?
Edit: See the Image of Google Keep List.
There is no editable Checkbox provided by android what you can do is set listeners on your checkboxes, and then have to capture the events like when checkbox is checked and when is it unchecked to make your editexts work the way you want.A sample way to start is :
CheckBox someCheckBox= (CheckBox) findViewById (R.id.someID);
someCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
//CODE TO MAKE THE EDITTEXT ENABLED
}
else
//CODE TO MAKE THE EDITTEXT DISABLED
}
});
However there are other ways too,to achieve this task, but you can kick off with this right away. Hope it helps.

Android RadioButton Confirm Selection

In my Android Application it's required to give a notification(warning) message before user change Radio Group Selection.
Basically I am trying to give a dialog message (that have warning message and YES/NO buttons to confirm change) when user click any other radio button within that Radio groiup.
If user presses YES then to change readio button selection with what user wanted to change, otherwise (if press NO) to select back with what was selected before.
I don't see any option in onCheckedChanged method when listen to OnCheckedChangeListener. What would be the best way to do this. Thanks
EDITS
I'm providing the warning message from a Dialog within onCheckedChanged method with option to Confirm the change (with YES/NO buttons). Problem is when user don't want the new selection after seeing the warning, I need a way to know the prevoiusly selected Radio Button to revert user's new selection.
public void onCheckedChanged(RadioGroup group, int checkedId)
The above method provides "checkedId" but how to know which Radio Button had selected before. It's required when user want to Cancel change..
Can do this by tracking the ealier selection defining a class level variable to hold old Radio button ID or some other logic like that. But there should be a straight forward way in Radio group to cancel new selection (by selecting old one back). I looked for beforeRadioCheckChange Type listener but didn't manage to find
You can store selected button before (when you actually set which one of radio buttons should be checked initially):
int selectedButton = mRadioGroup.getCheckedRadioButtonId();
And update it inside onCheckedChanged callback:
selectedButton = group.getCheckedRadioButtonId();
when user confirms change. Otherwise return checked state to the last selectedButton.
there is no a method in RadioGroup that enables you to revert your action, however you can easily achieve this by holding the id of selected RadioButton in an outside variable, and use it to revert your changes back:
RadioGroup radio;
static int buttonChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
radio = (RadioGroup) findViewById(R.id.radioGroup);
buttonChecked = radio.getCheckedRadioButtonId(); // be sure to get the checked button id first time before assigning the onCheckedChange
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Raise Dialog
if(yes){ // User confirmeed
buttonChecked = checkedId;
}else{ // User refused
if(buttonChecked != -1) // to prevent app from crashing if nothing is already selected
radio.check(buttonChecked);
else
radio.clearCheck();
}
}
});
}

How to clear checkboxes when reset button is clicked

In my project I have a number of checkboxes in a linear layout. When running the project by default all checkboxes are unchecked and I need to check some checkboxes. Below the checkboxes there is a reset button. When the reset button is clicked all the checkboxes are unchecked. How do I do this? Please help.
Call this in onClick()of Reset button.
if (checkBox1.isChecked()) {
checkBox1.setChecked(false);
}
if (checkBox2.isChecked()) {
checkBox2.setChecked(false);
}
.
.
.
and so on
To Uncheck all checked CheackBoxes keep references of the checked Checkboxes in ListView/Array and when reset button is clicked mark them as unchecked,
ListView <CheckBox> selectedcheckBox = new ListView<CheckBox> ();
when Checkbox is Checked---
selectedcheckBox.add(referanceofckeckbox).
now when reset button is clicked
public void onclick(View v){
for(CheckBox cb : selectedcheckBox){
cb.setChecked(false);
}
}
Hope it help.
if (checkBox.isChecked()) {
checkBox.toggle();
}
use this for all the checkboxes used.
For me it worked like this:
CheckBox checkBox = (CheckBox) findViewById(R.id.check_box);
checkBox.setChecked(false);
I see this is old stuff, but has no valid answer so maybe this one helps anyone.
jQuery + CSS selectors work very well for this. If you just want to uncheck all those checkboxes that are checked you just need the following code:
$('[type=checkbox]:checked').prop('checked', false);
While if you want to toggle all you can add variable to hold the checked status like this:
var isChecked = $('[type=checkbox]').is(':checked');
$('[type=checkbox]').prop('checked', !isChecked);

Listview with images & checkboxes restrict the user to select 5 checkboxes only

I had listview with images and checkboxes wher i have to restrict the user to check 5 checkboxes and disable or make invisible other checkboxes in the list view and whenever user uncheck's one of the five checkboxes that was previous checked should make checkbox enabled or visible again.
you can do this by counter variable as you have to check for all the check box status using iterator also or you can put in click event of checkbox to check whether it reached to limit or not if it reached already after checked the 5th one then disable the another checkbox and when it less then then enable it reset of checkbox
If you are just looking to prevent the user from selecting more than 5 - meaning they have to manually uncheck items - just use a counter variable like pratik suggested. If you want to automatically uncheck the oldest thing the user checked, I would use a queue of the selected indexes. then you can pop the oldest thing off, uncheck it, and add the new index to the queue. you could do all of this in an onItemClickListener or onItemSelectedListener
You can use onCheckedChangeListener.
Add a private integer:
private int checkedCounter;
Initialize it:
checkedCounter = 0;
Set listener:
yourCheckbox = (CheckBox) findViewById(R.id.itsId);
yourCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (checkedCounter == 5 && isChecked)
{
yourCheckbox.setChecked(false);
}
else if checkedCounter == 5 && !isChecked)
{
checkedCounter--;
}
else if (checkedCounter < 5)
{
(isChecked ? checkedCounter++ : checkedCounter--);
}
}
});
I can't run this code right now so check the conditions.
Actually it can be done also in another way: When 5 boxes are checked you can use setEnabled(false) method on others.

Can a RadioGroup span more than one layout?

I have sucessfully made and used RadioGroup's before in xml, but each time there was a set of radio buttons in succession, all within the same LinearLayout. Now I wish to define a set of radio buttons to be part of a group, but they are not in the same layout. My start and end code for the group is:
START:
<RadioGroup android:id="#+id/radioGroup1" >
END:
</RadioGroup>
If I place this around each button individually, then it compiles, but the buttons don't act as radio buttons (i.e. activating one did not de-activate the others). If I try to place the "start" before any of the buttons and put the "end" after the last of them, then I get compilation errors.
Store the RadioButtons in an array. Instead of grouping them in a RadioGroup, you have to enable/disable them yourself. (un-tested so no copying/pasting )
declare these variables
private ArrayList<RadioButton> mGroup = new ArrayList<RadioGroup>();
private CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
for(RadioButton btn : mGroup)
btn.setChecked(false);
buttonView.setChecked(true);
}
}
Somewhere in your activity:
mGroup.add(your radiobuttons); // e.g. (RadioButton)findViewById(R.id.radio_button1);
mGroup.add(another radiobutton);
for(RadioButton btn : mGroup)
btn.setOnCheckedChangeListener(mListener)
Maybe you have to invalidate your Buttons after checking/unchecking them, to cause a redraw
Unfortunately the SDK does not directly support doing this, you would need to create a custom "group" to manager the buttons.
All the mutual exclusion logic for each RadioButton is managed by RadioGroup, so all the buttons have to be added to the same group. RadioGroup is a subclass of LinearLayout, so this inherently means they also need to all be in the same layout. RadioGroup manages each button's checked status by iterating through its children, which is why the two can't be divorced.
Here is a link to the RadioGroup source code as a starting point, you could create a custom Manager that uses the same logic here to manage the status of which button is checked in order to separate them from their layout status. RadioGroup basically just registers itself as an OnCheckedChangeListener for each child that is a RadioButton and then controls the check status of all the buttons based on user events.
HTH
Here's a refined and tested version of the first part of Entreco's code:
final ArrayList<RadioButton> mGroup = new ArrayList<RadioButton>();
CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
for(RadioButton btn : mGroup) {
if (buttonView.getId() != btn.getId() && isChecked) {
btn.setChecked(false);
}
}
}
};
It will uncheck only the other buttons and only if the state of the clicked button changed from unchecked to checked.
#Entreco answer can cause recursive call to onCheckedChanged which is fixed by #Twilite answer.
But #Twilite answer also has a problem and that's the id of views without explicit id may not be unique. If that happen, you may see either multiple selected radio buttons or none of them being checked. So, it's safer to either set a unique id or a unique tag for each one:
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
for (RadioButton btn : mGroup)
if (!btn.getTag().equals(compoundButton.getTag()))
btn.setChecked(false);
}
}

Categories

Resources