Android RadioGroup OnCheckedChangeListener - android

I have an Activity which implements both Checkbox.OnCheckedChangeListener and RadioGroup.OnCheckedChangeListener The groups are both dynamically generated and passed the same Activity as the listener.
However, when I click on a RadioGroup, the RadioGroup.OnCheckChangeListener is completely ignored but here's where it gets weird. It triggers CheckBox.OnCheckChangeListener! I tried casting the activity to the RadioGroup listener before passing it, but RadioGroup cannot even accept it, only the CheckBox listener gets through.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_MULTI_ANSWER")) {
String selected = buttonView.getText().toString();
if (subquestion.getAnswer().getDataList() != null) {
Answer answer = subquestion.getAnswer();
ArrayList<String> checked = answer.getDataList();
if (checked.contains(selected)) {
checked.remove(selected);
Log.d("Checkbox" + buttonView.getId(), "unchecked");
} else {
checked.add(selected);
Log.d("Checkbox" + buttonView.getId(), "checked");
}
} else {
ArrayList<String> checked = new ArrayList<String>();
checked.add(selected);
subquestion.getAnswer().setDataList(checked);
Log.d("Checkbox" + buttonView.getId(), "checked");
}
}
if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_SINGLE_ANSWER")) {
RadioGroup group = buttonView; //CAN'T BE DONE
String selected = group.getFocusedChild().getId() + "";
subquestion.getAnswer().setData(selected);
Log.d("Radiobutton " + selected + group.getFocusedChild().getId(), "selected");
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//This does NOTHING, can't even be passed to the RadioGroup as a listener
}
How do I get the RadioGroup from the buttonView? I generate everything in code and it's different every time so there are no static id's to determine what's clicked. I pass an id to the radiobuttons to let me know which is which but I can't get to it like this.
It works perfectly for the checkboxes, it's just that Android seems to throw the wrong event and uses the wrong event handler for RadioGroup.
Thank you for reading!

Call this method for RadioGroup.OnCheckChangeListener and pass RadioGroup as argument
public void onRadioChangeListener(RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// write your code here
}
});
}

Related

how to validate fragment RadioGroup inside from MainActivity Button click?

I have a Fragment with Dynamic Radio group. When User Select any radio button. I am Passing value instead of radio button and load another thing with next button click from MainActivity. But If User not selected any radiobutton, MainActivity "NextButton" need to check Validation like Radiogroup to radiobutton ischeck() or not, If not Then need to show Toast.
Sorry for my Bad English.
Radio Grounp Code in Fragment:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton= group.findViewById(checkedId);
answer = radioButton.getText().toString();
// Toast.makeText(getActivity(), ""+answer, Toast.LENGTH_SHORT).show();
answerModel = new AnswerModel(id, question, answer);
Double referId = (Double) questionDataModel.getOptions().get(checkedId - 1).getReferTo();
nextId = referId.intValue();
// Toast.makeText(getActivity(), ""+referId, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), ""+answerModel.getId()+"\n"+answerModel.getAnswer()+"\n"+answerModel.getQuestion(), Toast.LENGTH_SHORT).show();
sendDataInterface.sendata(nextId, answerModel);
}
});
Data Receive from MainActivity with NextButton:
I need to check Validation within this method actually
#Override
public void sendata(int data, AnswerModel answerModel) {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToNextQuestion(data);
// Toast.makeText(MainActivity.this, ""+data, Toast.LENGTH_SHORT).show();
}
});

Getting the isChecked() value from CheckBox or RadioButton

I have set the click event listener on a number of CheckBox and RadioButton views. Both of these view types have an isChecked() method. I can get the state of either one by casting to its type for every single switch case, but can I get the state just in a general sense for either of them before I enter the switch cases?
#Override
public void onClick(View view) {
boolean checkState;
switch (view.getId()) {
case R.id.radio_button_1:
checkState = ((RadioButton) view).isChecked();
// ...
break;
case R.id.check_box_1:
checkState = ((CheckBox) view).isChecked();
// ...
break;
// more check boxes and ratio buttons ...
}
}
This question has a similar title to this one, but there was too much code there for me to easily understand if they were asking the same thing.
While I was in the process of writing this question, I found an answer, which I will post below. However, if there is a better answer, I will accept it.
Consider one RadioButton and one CheckBox
RadioButton button = (RadioButton) findViewById(R.id.radio_button);
button.setOnCheckedChangeListener(listener);
CheckBox box = (CheckBox) findViewById(R.id.checkbox);
box.setOnCheckedChangeListener(listener);
Both have a single listener
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView instanceof CheckBox ){
Toast.makeText(getApplicationContext(), "ChechBox " + String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "RadionButton " + String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
}
}
};
If there are many still we can use a single listener as follows
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView instanceof CheckBox ){
final ChechBox b = (ChechBox)buttonView;
switch(b.getId()){
case R.id.first_checkbox:
. . . . . . . .
}
}else {
final RadioButton r = (RadioButton)buttonView;
switch(r.getId()){
case R.id.first_radio
. . . . . . . . . . .
}
}
}
};
You need to attach all of the views to this listener
Direct Answer
As #MikeM answered in the comments, you can use instanceof to check once for CompoundButton or Checkable and cast to that.
#Override
public void onClick(View view) {
boolean checkState = false;
if (view instanceof Checkable) {
checkState = ((Checkable) view).isChecked();
}
switch (view.getId()) {
// ...
}
}
Better Answer
However, as #MikeM also mentioned, you should be using an OnCheckedChangeListener rather than an OnClickListener. There are two similar checked changed listeners:
CompoundButton.OnCheckedChangeListener
RadioGroup.OnCheckedChangeListener
The CompoundButton listener can be used for a CheckBox or a RadioButton. However, if all the radio buttons in a RadioGroup had this set, the listener would get called twice, once for the button getting turned off and once for the button getting turned on. Thus, it is better to use the RadioGroup listener for radio buttons.
So add the RadioGroup.OnCheckedChangeListener to the RadioGroup and the CompoundButton.OnCheckedChangeListener to each CheckBox.
// set RadioGroup.OnCheckedChangeListener
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(radioGroupListener);
// set `CompoundButton.OnCheckedChangeListener`
CheckBox cb1 = (CheckBox) view.findViewById(R.id.check_box_1);
cb1.setOnCheckedChangeListener(checkBoxListener);
CheckBox cb2 = (CheckBox) view.findViewById(R.id.check_box_2);
cb2.setOnCheckedChangeListener(checkBoxListener);
// ...
where the listeners are implemented as follows:
Radio Buttons
The isChecked() value is true for whatever RadioButton id is returned by the RadioGroup listener.
RadioGroup.OnCheckedChangeListener radioGroupListener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
// checkedId is the id of the newly checked radio button
switch (checkedId) {
case R.id.radio_button_1:
// ...
break;
case R.id..radio_button_2:
// ...
break;
// ...
}
}
};
Check Boxes
The isChecked value is directly passed in to the CompoundButton listener.
CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
switch (compoundButton.getId()) {
case R.id.checkbox_1:
// ...
break;
case R.id.checkbox_2:
// ...
break;
}
}
};

In android, onCheckedChanged of a Radiogroup is not triggered when I Programmatically set a Radiobutton by call setChecked(true)

In my application, I need to programmatically set a radiobutton and expect the onCheckedChanged of a Radiogroup to be triggered so that I can do something in it.
Code to set a radiobutton programmatically.
LayoutInflater inflater = LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.footer, null);
RadioButton btn = (RadioButton)view.findViewById(R.id.footer_btn_course);
btn.setChecked(true);
And in another activity, I did something like:
public class MainActivity extends ActivityGroup implements RadioGroup.OnCheckedChangeListener{
protected void onCreate(Bundle savedInstanceState){
mRadioGroup = (RadioGroup)findViewById(R.id.footer_radio);
mRadioGroup.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId){
RadioButton btn = (RadioButton)findViewById(checkedId);
if(btn != null){
do_something();
}
}
}
However, looks like this way doesn't work, the onCheckedChanged was never called. Anyone know what I should do? Thanks.
To fire a radio check box for the default when initializing. Set everything to unchecked with the clearCheck method. Then, set the handler and finally set the default and your handler will fire.
itemtypeGroup.clearCheck();
then, same as usual add a listener:
mRadioGroup = (RadioGroup)findViewById(R.id.footer_radio);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.clearCheck();
RadioButton btn = (RadioButton)view.findViewById(R.id.footer_btn_course);
btn.setChecked(true);
I am not sure for the issue, but it may be you miss refer your radio group id.
Try this instead to see the effect (inside your onCreate()):
RadioGroup rdGroup = (RadioGroup) findViewById(R.id.footer_radio);
rdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton btn = (RadioButton)findViewById(checkedId);
if(btn != null){
do_something();
}
}
});
Or may be (RadioButton)findViewById(checkedId) return null.
Try Spinner if your case gets ambiguous.
Instead of btn.setChecked(true);
Used btn.performClick(); this will work.
I had the same problem..
and here is my approach:
class Myclass extends Activity{
protected void onCreate(Bundle savedInstanceState) {
radiogroup = (RadioGroup) findViewById(R.id.radiogroupDecisionUncertain);
radio1 = (RadioButton) findViewById(R.id.radiobuttonNo_U);
radio2 = (RadioButton) findViewById(R.id.radiobuttonYes_U);
// declare the onCheckChangedListener
radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (checkedId == radio1.getId()) { //do something
} else { // do other thing
}
}
});
radiogroup.check(radio1.getId());
}
}
Notice that i set the checked radio button after registering the listener..
Implement OnCheckedChangeListener instead of RadioGroup.onCheckedChangeListener that will work.
public class MainActivity extends ActivityGroup implements OnCheckedChangeListener{
.....
}

Radio Button in Radio Group does not show checked after clicking on it

I am having a problem with a radio button that is in a radio group.
I have an app that is a quiz application and I ask 5 questions.
When run the application in my Android emulator all the questions have no problem but only on the 3rd question. When I click with my mouse on the radio button it seems toggle to a checked state but then it unchecks right away. Has anyone seen this kind of behavior?!
I setup this Radio group and dynamically add 4 radio buttons in a radio group and then use an OnCheckedChangeListener() event to capture the change.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0; i<=3;i++)
{
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
if (btn.isPressed() && questNo < 6)
{
if (corrAns[questNo-1].equals(btn.getText()) && flag==true)
{
Log.e(LOG_TAG,"onCheckedChanged: correct answer = btn Text");
score++;
flag = false;
checked = true;
}
else if(checked==true)
{
Log.e(LOG_TAG,"onCheckedChanged: correct answer != btn Text");
score--;
flag = true;
checked=false;
}
}
}
Log.e(LOG_TAG, "Score:"+ Integer.toString(score));
}
});
I have noticed that it happens randomly on different questions and only on first radiobutton that is selected but if you select another one after then the functionality returns to normal. Any ideas?
I had the same bug. I'm also using dynamic radioGroups and buttons. This is working for me:
private OnCheckedChangeListener rblLikert_Listener = new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedIndex = group.getCheckedRadioButtonId();
if(selectedIndex != -1)
{
m_likertValue = radioButtonValue;
int buttonId = group.getCheckedRadioButtonId();
Logger.i("button id: " + String.valueOf(buttonId));
RadioButton selectedButton = (RadioButton)findViewById(buttonId);
selectedButton.toggle();
Logger.i(" is checked: " + String.valueOf(selectedButton.isChecked()));
}
}
};

Android Radio Button

I have a radio button group in Android which looks something like:
Choose Color:
Red
Blue
Orange
Green
I need to get selected radio button and also its value.
I have 4 radiobuttons in this manner within radiogroup rg
rb1a=(RadioButton)findViewById(R.id.rb1a);
rb1b=(RadioButton)findViewById(R.id.rb1b);
rb1c=(RadioButton)findViewById(R.id.rb1c);
rb1d=(RadioButton)findViewById(R.id.rb1d);
tv1=(TextView)findViewById(R.id.tv1);
next1=(Button)findViewById(R.id.next1);
rg=(RadioGroup)findViewById(R.id.rg);
// I have error after this line.please help
rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
}
});
you can test the radion button with the isChecked() function.
for ex:
if(radio1_red.isChecked())
{
txtView.setText("Red button is checked");
}
Have a look at this Example .
You can also refer this Page - Form Stuff given in android-sdk pages.
Do this for getting selected radio button and also its value:
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
like you can see on the android documentation
http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html
the OnCheckedChangeListener has only the method
onCheckedChanged(RadioGroup group, int checkedId) and doesn't contain the method
public void onCheckedChanged(CompoundButton arg0, boolean arg1) -> remove it and try again.
You find an example here:
http://developer.android.com/guide/tutorials/views/hello-formstuff.html
regards

Categories

Resources