Difficult to understand how eventlisteners work in Java?

Asked

Viewed 27 times

1

Greetings dear fellow programmers

Are you all right? I hope so

I’m doing this publication because I’m having a lot of difficulty to understand a specific parameter of the listeners of Android Studio, in specific of Onclick, and as I realized that many functions of the development environment carry this same structure, I decided to do this topic

The code in question proposed by the exercise is as follows:.

public class MainActivity extends AppCompatActivity {

private EditText precoGasolina;
private EditText precoEtanol;
private Button botaoVerificar;
private TextView textoResultado;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    precoGasolina =(EditText)findViewById(R.id.txt_gasolina);
    precoEtanol = (EditText)findViewById(R.id.txt_etanol);
    textoResultado = (TextView)findViewById(R.id.lbl_resultado);
    botaoVerificar = (Button)findViewById(R.id.btn_calcular);

    botaoVerificar.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            //Recupera valores digitados
            String textoPrecoAlcool = precoEtanol.getText().toString();
            String textoPrecoGasolina = precoGasolina.getText().toString();
            //Conveterter valores strings para numeros;
            Double valorEtanol = Double.parseDouble(textoPrecoAlcool);
            Double valorGasolina = Double.parseDouble(textoPrecoGasolina);

            double resultado = valorEtanol/valorGasolina;

            if (resultado >= 0.7){
                textoResultado.setText(resultado + "É melhor utilizar gasolina");
            }else{
                textoResultado.setText(resultado + "É melhor utilizar Etanol");
            }
        }
    });
}
}

My big doubt lies within the

onClick(View v){

I know what the View v argument works for, it serves to access button attributes, but my doubt is how I can pass an argument without referencing the button and it can interpret that I’m treating the button object?

No answers

Browser other questions tagged

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