android radiobutton check after clearing check issue - android

friends. I'm having a really silly problem with radiogroup. Yet I'm unable to find solution.
I will try to describe how to reproduce my problem:
I have radiobutton group and two buttons inside.
I select one of them, lets say 1st one.
Then I'm clearing selection by calling radioGroup.clearCheck()
After I'm trying to select 1st button, but its not checking.
If I check 2nd, it checks normally.
If I check 1st after checking 2nd it also works normally.
This may sound crazy, yet I can't fix it. Please help me, thanks in advance.
I use
#Override
protected void init() {
View view = View
.inflate(getContext(), R.layout.wo_task_yn_result, null);
performed = (RadioButton) view.findViewById(R.id.yn_yes);
notPerformed = (RadioButton) view.findViewById(R.id.yn_no);
radioGroup = (RadioGroup) view.findViewById(R.id.yn_options);
performed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
Log.d(YES, "verify");
if (isChecked) {
Log.d(YES, "checked");
result = YES;
}
}
});
notPerformed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
Log.d(NO, "verify");
if (isChecked) {
Log.d(NO, "checked");
result = NO;
}
}
});
addView(view);
}
To create buttons and
#Override
public void clear() {
radioGroup.clearCheck();
result = "";
}
for clearing them

I had the same problem. Was unable to select the first radioButton in the group, but could select the other two. And after selecting the second radioButton, I could select the first one as well. I resolved it by doing a single radioGroup.clearCheck() instead of individual radioButtonA.setChecked(false)

Use OnCheckedChangeListener and make use of the method setSelected(true) or setChecked(true).

if u want to uncheck radio button try this method:
#Override
public void clear() {
performed.setChecked(false);
nonperformed.setChecked(false);
}

Related

How to check state Changing of CheckBox in android?

I want to check if my Checkboxes are checked to change some values.
I got the answer for radioButton which is inserted to a RadioGroup and we can simply use :
radioGroup.setOnCheckedChangeListener(new new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{ . . . }
}
i'm looking for something like this ,However this approach is differ from Checkboxes because there is no widget like CheckboxGroup to use setOnCheckedChangeListener On it .
For example i have checkbox1 and checkbox2. how can i get as long as these two checkboxes are checked to changing some value like :
if(checkbox1==isChecked && checkbox2==isChecked)
//Do sth ...
else
//Do sth Different
EDIT : Maybe i could not explain my problem perfectly , this is just like question below but for Checkboxes
How to check state Changing of Radio Button android?
As commented you can use checkboxRef.isChecked()
if(checkbox1.isChecked() && checkbox2.isChecked()){
}
else{
}
but I want to use them in a different function , may globally access
to this checkboxes
You can use sharedPreference and with a utility class to store the state of your checkbox.
SharedPreferences helper class
This is way to check which checkbox is checked..
if(checkbox1.isChecked())
{
//means checkbox1 is checked...
}else
{
//means checkbox2 is checked...
}
If you want to set an event listener to detect when a change is made you can use:
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
//Code here
} } );
On the other hand if you want to check if it is checked you can use:
if(checkbox.isChecked()){
//Code here
}
Finally i got the answer , first of all I need to set onclick attribute as the same for all of the checkboxes , and check my Needed for approach desire output in the onClick Function,
Xml:
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="func"
android:text="1"
android:id="#+id/c1"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2"
android:onClick="func"
android:id="#+id/c2"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3"
android:onClick="func"
android:id="#+id/c3"/>
JavaCode:
public void func(View view) {
CheckBox checkBox1 = (CheckBox)findViewById(R.id.c1);
CheckBox checkBox2 = (CheckBox)findViewById(R.id.c2);
CheckBox checkBox3 = (CheckBox)findViewById(R.id.c3);
if(checkBox1.isChecked() && checkBox2.isChecked() && (!checkBox3.isChecked()))
{
Next = true;
}
else
{
Next = false;
}
}
checkBox1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox1.isChecked() && checkBox2.isChecked()){
}
}
});

RadioGroup.check() make OnCheckedChangeListener.onCheckedChanged called twice [duplicate]

I've been struggling with an issue of programmatic checking of a RadioButton, which is situated in a RadioGroup. It seems that a single check() call raises three events - once for the first RadioButton and twice for the second, which is my target. At the same time clicking on the second RadioButton in the interface causes only one event to appear, which is correct.
So, is there a way to avoid multiple event raising ?
public class RadiogroupActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup r = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton b = (RadioButton) findViewById(R.id.radio1);
r.setOnCheckedChangeListener(onPromobuttonsClick);
r.check(R.id.radio1);
}
private OnCheckedChangeListener onPromobuttonsClick = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("x", "x");
}
};
}
So, is there a way to avoid multiple event raising ?
Call b.setChecked(true); instead.
A quick look through the source code confirms that RadioGroup#check() really does call the OnCheckChangedListener three times...
When the current selection is unchecked,
When the new RadioButton is checked, and
When the RadioGroup saves which RadioButton is now checked.
Odd quirk.
Simply post your r.setOnCheckedChangeListener(onPromobuttonsClick); line in onResume() method. It is works for me.
So this is an old one but I also got a similar behavior. A workaround that I found was to call the toggle() method of RadioButton instead of the check() method of RadioGroup.
So in this example, you woulod just need to swap
r.check(R.id.radio1);
with
b.toggle();
since b is already the view with id R.id.radio1.
I had this problem when I wanted to log analytics for radio button presses, but the way the radio groups calls were being handled with .check() caused onCheckedChangeListener to get called multiple times (which sent too many events).
I handled it the following way to only get one event per click:
// create listeners so we don't duplicate the creation in for loop
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// whatever you want to do here
}
};
// add on click listener to all radio buttons
int buttonCount = buttonGroup.getChildCount();
for (int i = 0; i < buttonCount; i++) {
if (buttonGroup.getChildAt(i) instanceof RadioButton) {
buttonGroup.getChildAt(i).setOnClickListener(onClickListener);
}
}
This is a old question but I didn't found a complete answer yet that cover my issue. But thanks to #Hellojeffy suggestion I figured a way to handle the situation when RadioButton trigger multipletimes when using setOnCheckedChangeListener().
The idea is to add a click on each view inside the RadioGroup and trigger a event on click, instead a event on check changes.
for (child in radioButtonGroup.children) {
if (child is RadioButton) {
when (child.id) {
R.id.rb1 -> child.setOnClickListener { onRb1Click(...) }
R.id.rb2 -> child.setOnClickListener { onRb1Click(...) }
R.id.rb3 -> child.setOnClickListener { onRb1Click(...) }
...
}
}
}

saving the state of radiobuttons

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages where each page has only one question and 4 answers(a,b,c,d). For this task I have defined 4 radiobuttons for each question. What I want to obtain is that if any radiobutton is checked , the other radiobuttons are unchecked (radiobuttons checked false) . And i want that when the user goes thorugh differentes pages the value can be retrieved. I have tried this code , however it worked fine with selecting one answer and uncheck the others , but it didnt work for saving the state of the radiobuttons even though i used shared preferences .
public class Page1 extends Activity {
RadioButton r1a , r1b , r1c , r1d ;
Button b1n ; // this is a next-button that will navigate to page2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SharedPreferences pref ;
r1a = (RadioButton) findViewById(R.id.Q1a);
r1b = (RadioButton) findViewById(R.id.Q1b);
r1c = (RadioButton) findViewById(R.id.Q1c);
r1d = (RadioButton) findViewById(R.id.Q1d);
b1n = (Button) findViewById(R.id.B1n);
pref = getSharedPreferences("Answers", 0);
final Editor editor = pref.edit();
r1a.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1a.isChecked()){
r1b.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1b.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1b.isChecked()){
r1a.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1c.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1c.isChecked()){
r1a.setChecked(false);
r1b.setChecked(false);
r1d.setChecked(false);
}
}
});
r1d.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1d.isChecked()){
r1c.setChecked(false);
r1a.setChecked(false);
r1b.setChecked(false);
}
}
});
// i use this to save the state , but it fails :(
editor.putBoolean("questionA", r1a.isChecked());
editor.putBoolean("questionB", r1b.isChecked());
editor.putBoolean("questionC", r1c.isChecked());
editor.putBoolean("questionD", r1d.isChecked());
editor.commit();
}
public void move12(View view) { // instantiated when b1n is clicked
Intent intent = new Intent(this , P2.class) ;
startActivity (intent) ;
}
}
i have two questions here :
is this code ok ? or is there a better idea for handling the checked buttons ?
the shared preference does not work , anytime i return to page1 all the radiobuttons are unchecked and the state fail to be saved. what is the cause of the problem ?and how can it be resolved ? any ibeads please .
Your code for saving state is ok. Your radioButtons are unchecked because nowhere in Page1 you actually read from SharedPreferences and set their state. You could add this in onCreate():
r1a.setChecked(pref.getBoolean("questionA", false));
r1b.setChecked(pref.getBoolean("questionB", false));
r1c.setChecked(pref.getBoolean("questionC", false));
r1d.setChecked(pref.getBoolean("questionD", false));
First though, check if preference file is present and if states of each buttons have been saved.
You can sort of truncate your onCheckChangedListeners to just one and then have a switch that checks to see which RadioButton was clicked, but the way you did it is fine.
As per saving the data, it doesn't look like you're attempting to read the data that you saved. First of all, you should put all of your data saving inside the move12 method. Secondly, try adding something like this to your onCreate:
bool aChecked = prefs.getBoolean("questionA",false);
if(aChecked)
r1a.setChecked(true);
Do that for all four.

How to force RadioGroup to select only one RadioButton at a time programatically?

I am designing customize form programmatically where user can put a question and can add multiple options using radio buttons. I have taken RadioGroup and i am adding radio buttons in it. But while selecting i want only one radio button get selected at a time. How to implement it programmatically. Please help me..
Here is my code
final RadioGroup radioGroup = new RadioGroup(getApplicationContext());
radioGroup.setId(1);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
RadioButton radioButtonView = new RadioButton(getApplicationContext());
radioButtonView.setId(i++);
radioButtonView.setText(addnew);
radioGroup.addView(radioButtonView, p);
loption.addView(radioGroup, p);
Thanks in advance,
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "onCheckedChanged " + buttonView.getId());
mRadioGroup.clearCheck();
if (isChecked) {
mRadioGroup.check(buttonView.getId());
}
}
It seems that you are making a new RadioGroup for every RadioButton.
You should add every new RadioButton to the same RadioGroup. The RadioGroup will then make sure only one RadioButton can be selected at the time.
I have tried the same problem when I insert LinearLayout to put the radiobuttons in a grid.
I solved this way.
Considering that we have more RadioGroups, we know the RadioButton that was pressed. For this reason, just remove the listener from all of your RadioGroups and then deselect all the RadioButtons, resetting onCheckedChangeListener to your RadioGroup.
This is my code:
onCheckedChangeListener= new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
clearAllRadioButton();
((RadioButton) binding.getRoot().findViewById(i)).setChecked(true);
resetListenerRadioGroup();
}
};
onCheckedChangeListener2 = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
clearAllRadioButton();
((RadioButton) binding.getRoot().findViewById(i)).setChecked(true);
resetListenerRadioGroup();
}
};
binding.rg.setOnCheckedChangeListener(onCheckedChangeListener);
binding.rg2.setOnCheckedChangeListener(onCheckedChangeListener2);
private void clearAllRadioButton() {
binding.rg2.setOnCheckedChangeListener(null);
binding.rg.setOnCheckedChangeListener(null);
binding.failed.setChecked(false);
binding.draft.setChecked(false);
binding.sent.setChecked(false);
binding.inbox.setChecked(false);
}
private void resetListenerRadioGroup(){
binding.rg2.setOnCheckedChangeListener(onCheckedChangeListener2);
binding.rg.setOnCheckedChangeListener(onCheckedChangeListener);
}
*do not use the radioButton's clearCheck () because it does not respond well when resetting listeners.
Check this out it will work for you:
First Get RadioButton:
RadioButton radioBalls = (RadioButton) findViewById(R.id.radioGameInPlayBalls);
RadioButton radioTime = (RadioButton) findViewById(R.id.radioGameInPlayTime);
radioBalls.setOnCheckedChangeListener(this);
radioTime.setOnCheckedChangeListener(this);
Now in #overide method:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean c) {
switch (buttonView.getId()) {
case R.id.radioGameInPlayBalls:
if (radioTime.isChecked() && c) {
radioBalls.setChecked(false);
return;
}
radioBalls.setEnabled(c);
break;
case R.id.radioGameInPlayTime:
if (radioBalls.isChecked() && c) {
radioTime.setChecked(false);
return;
}
radioTime.setEnabled(c);
break;
default:
break;
}
}
You should check a radio button using RadioGroup, not radio button directly. Below, I populate radio group from list of options and get the radio button id of option to be checked and check the corresponding button after populating radio group. Same goes if you determine the checked option by index.
int checkedId = -1;
for(JsonElement option : options){
RadioButton radioButton = new RadioButton(getContext());
radioGroup.addView(radioButton);
if(checkedOptionId.equals(id)){
checkedId = radioButton.getId();
}
}
radioGroup.check(checkedId);

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