Why do some actions give error if I do not specify View as parameter in Android?

1

I'm creating a test app with the basic knowledge I got on android since previously I was a java programmer. All of the tutorials I searched for put the View class as the default parameter in their methods, but no one explained why, and hj I was testing in this application if it worked without passing the class View as a parameter and incredibly failed! I would like to know why it is necessary to pass the View class as a parameter of my methods and if in some case I can omit (specify)?

public void abrirBrowser(View view) {
    Uri url = Uri.parse("http://google.com.br");
    Intent i = new Intent(Intent.ACTION_VIEW, url);
    startActivity(i);
}
    
asked by anonymous 09.06.2017 / 04:15

1 answer

3

The view as a parameter is only required in methods that you define in the "android: onclick" attribute of the views in XML, because internally the Android directs an onClickListener to the same via the defined method (in its case, the "openBrowser" ) when they are inflated in the app, and this listener is an interface that implements the onClick () method that requires a view as a parameter.

For example, instead of setting the method in XML (and letting Android create the listener automatically), you could manually set the listener in code that way, which would call your method without having to pass the view as a parameter (since you already passed the interface method):

Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        abrirBrowser();
    }
});

For methods you normally create, there is no need for required parameters.

    
09.06.2017 / 05:27