views:

409

answers:

1

I was writing a simple test application. There are two radio buttons within the app. There id's are "radio_red" and "radio_blue". I wanted to create an onClickListener event that read the text associated to the button and then returned a basic "Right" or "Wrong" toast.

Here is a sample of the code:

private OnClickListener radio_listener = new OnClickListener() {
    public void onClick(View v){
        RadioButton rb = (RadioButton) v;
        String ans =  rb.getText().toString();
        String an1 = "";

        if (ans.trim() == "Yes") {
            ans = "That's Right.";
        }
            else if (ans.trim() == "No") {
                ans = "thats wrong.";
            }
            else {
                ans = "none.";
            }

        Toast.makeText(v.getContext(), ans , Toast.LENGTH_SHORT).show();
    }

So far no joy. Here is my code snippet. I've checked my "main.xml" and the text associated to the buttons are referneced correctly. I added trim to make sure of that. However, all that is ever returned in the toast is "none." What am I missing? Thanks in advance for any help.

+1  A: 

You want to deal with the RadioGroup, not the RadioButton. The RadioGroup can tell you more meta-details about the radio controls, like which one is checked. For example, in your listener you should use RadioGroup.getCheckedRadioButtonId().

Alternatively, you could add a listener to the RadioGroup itself that sets a toggle in the background, using RadioGroup.setOnCheckedChangeListener(). It has the capability of telling you which RadioButton was pressed.

Daniel Lew
Thanks Dan,I ended up setting using .setOnCheckedChangeListener(). A apreciated the helpful links.Bub
Bub