bubblegumandwine
bubblegumandwine

Reputation: 15

How to call a function with a View type parameter in another class in android

totally n00b in android programming with an embarrassing question, here it goes. For example, I have an onClick function with a view parameter like this:

public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:
        if (checked)
            // Ninjas rule
        break;
}
}

If I have to call this function in an another class in the same activity for example an AsyncTask class or whatever. How would I successfully do that? I have confusion with the parameter. Should I do it like:

View view; //local variable
onRadioButtonClicked(view); // it gives an error of being uninitialized

Or should I initialize it with a null value like:

View view = null;
//local variable onRadioButtonClicked(view); //this gives a null pointer exception

How do I call this function successfully without having a problem with the parameters?

Upvotes: 1

Views: 1197

Answers (1)

Spaceman Spiff
Spaceman Spiff

Reputation: 934

Generally you wouldn't call your onRadioButtonClicked() method yourself. The way you should use this in android is to set the onClick attribute in your xml like so onClick:onRadioButtonClicked. This way the android operating system will call the method for you when the user clicks the button.

The way android handles events like button presses is to use a callback method. Your callback for the radio button can be set programatically by calling radioButton.setOnClickListener() and passing in a radioButtonOnClickListener that you would create yourself. It can also be set in the xml as stated above. If you have a method like that in your class you should declare the onclick in the xml.

Read this for onclick for views in general

http://martin.cubeactive.com/android-onclicklitener-tutorial/

and here is some example radioButtonCode so you can see one in action https://github.com/asabbarwal/SimpleRadioButton

Upvotes: 1

Related Questions