One button click event

Asked

Viewed 1,997 times

1

Consider the following layout of a 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>

Amending I:

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

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

Amendment II:

public void clickNoBotao () {

        //Código aqui

}

Amendment III:

public void clickNoBotao (View view) {

        //Código aqui

}

Amendment IV:

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

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

I wonder if these alternatives and the event code are in accordance with the code Linearlayout

1 answer

2

the alternatives presented only to I and III are valid.

The class Button uses an interface implementation View.Onclicklistener to inform that the button has been clicked.

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

The SDK provides the possibility of the method onClick() of the interface can be indicated in the xml, through the attribute android:onClick, 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 alternative II is not valid.
The name can be different, as long as it is the same as in xml.

The alternative IV is also not valid because the Button class has no method called setOnClick().

Related: Advantage and advantage between onClick and setOnClickListener.

  • From now on I thank you for the answer , and I am now learning this area of android , because I am php programmer and c#, thanks, and I will study this theme,.

Browser other questions tagged

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