Click event of a button

1

Consider the following layout of an Activity :

<LinearLayout>
    <android.support.v7.widget.AppCompatButton
        android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="clickNoBotao"
        android:text="Login"/>
</LinearLayout>

Alterative I:

Button mBotao = (Button) findViewById(R.id.btnCreateAccess);

mBotao.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //Código aqui
    }
});

Alterativa II:

public void clickNoBotao () {

        //Código aqui

}

Alterativa III:

public void clickNoBotao (View view) {

        //Código aqui

}

Alterativa IV:

Button mBotao = (Button) findViewById(R.id.btnCreateAccess);

mBotao.setOnClick(new View.OnClick() {
    @Override
    public void onClick(View view) {
        //Código aqui
    }
});

I'd like to know if these alternatives and the event code conform to the LinearLayout     

asked by anonymous 26.08.2018 / 07:51

1 answer

1

Of the alternatives presented only to I and III are valid.

The Button class uses an interface implementation View.OnClickListener to inform you that the button was clicked.

This implementation must be associated with the button using the setOnClickListener() method.

The SDK provides the possibility that the onClick() method of the interface can be indicated in xml , using the android:onClick attribute, and implemented in Activity.

The method to be implemented must have the same signature as the interface method: public void onClick(View view) . That's why the II alternative is not valid. The name can be another, provided it is the same as the one indicated in the xml.

The IV alternative is also not valid, since the Button class has no method named setOnClick() .

Related: Advantage and disadvantage between onClick and setOnClickListener .

    
26.08.2018 / 12:51