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

Asked

Viewed 41 times

1

I’m creating a test app with the basic knowledge I acquired on android since I was a java programmer before. All the tutorials I researched people put the class View as a standard parameter in your methods, but no one explained why, and hj I went to test in this application if it worked without passing the class parameter View and it was incredibly wrong! I would like to know why it is necessary to pass the View class as a parameter of my methods and if in any case I can omit (specify)?

public void abrirBrowser(View view) {
    Uri url = Uri.parse("http://google.com");
    Intent i = new Intent(Intent.ACTION_VIEW, url);
    startActivity(i);
}
  • Can you exemplify this behavior?? It’s not all methods that need view.. It depends on what you’re going to do, but an example code to clarify

  • Let me give you an example:

  • Example given in the question update.

1 answer

3


A view as a parameter is only required in methods you define in the "android:onclick" attribute of the views in XML, because internally Android arrow an onClickListener to them through the method defined (in your case, the "open Rowser") 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 the code in this way, which would call your method without the need to pass the view as parameter (because 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 the methods you normally create, there is no need for mandatory parameters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.