Call method with parameter of View type, in another method

1

Examples of a method that requires a View

public void lista(View v) {
      Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

public void botaoAbrir (View view) { 
      Intent i = new Intent(this, NovoRegistro.class); 
      startActivity(i); 
}

I would like to call them within onCreate() or some other method that does not require View .

The way I tried and worked:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lista(new View(this));
}

But the question is, is that correct?

Can it be used like this without any problems? What other ways?

Is it advantageous for me to create a View for the class, and always call it?

    
asked by anonymous 01.02.2018 / 13:40

2 answers

0

Let's think a bit ... If the method requests a View as a parameter, it is because the processing performed in this method is inherent to the View that will be passed.

As we know a View is an element that is on the application screen (read What is a View on Android? ).

So, probably this method that requests this View makes changes to the application screen or even to% passed%. Following this logic, instantiating a View object is not correct, since it will only be instantiated and will not exist properly on the application screen. If the View is not required for the method to work then it does not make sense to pass the same parameter.

The correct approach is to get this View on the application screen and pass it on to the method using the View method and pick up the screen element that refers to this method.

To get the screen element, use the findViewById that was used to create the element in id of XML , below an example of how to do this:

View viewNaTela = findViewById(R.id.elementoNaTela);
lista(viewNaTela);
    
01.02.2018 / 14:16
1

I suppose this method is used by a Button whose click listener has been assigned, in its declaration in xml, with android:onClick=lista .

You seem to want this method to be called not only when you click the button but also by your code.

In these situations the usual is to have a private method with the code that wants to be executed in both situations. This method is called by the lista() method when the button is clicked and directly in the other case (its code).

It would look something like this:

public void lista(View v) {
      doListaClick();
}

private void doListaClick(){
    Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

No onCreate() would look like this:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        doListaClick();
}

As you can see, it is not necessary to use or "invent" any view to execute the code you want.

    
01.02.2018 / 15:17