10
I have a certain situation where we see that it is possible to create in the XML file a property called onClick
:
onClick:
XML:
<Button
android:layout_height="@dimen/edittext_min_height"
android:layout_alignParentLeft="true"
android:minWidth="120sp"
android:onClick="btnSend"
android:clickable="true"/>
Class:
public void btnSend(View view){
//faça algo
}
On the other hand we can also instantiate within the class the setOnClickListener()
:
setOnClickListener:
XML
<Button
android:id="@+id/btnSend"
android:layout_height="@dimen/edittext_min_height"
android:layout_alignParentLeft="true"
android:minWidth="120sp"/>
Class:
Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend .setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//faça algo
}
});
What would be the advantages and disadvantages between using onClick
and setOnClickListener
?
I haven’t had a real problem yet that prevented using onClick in xml. Just a few times I had to use the same screen more than once in the program for different situations. Maybe that’s it.
– Mr_Anderson
I don’t particularly like to use the
onClick
in XML, because if you, for some reason, delete the methodbtnSend
of your class, will not fail to compilation, and yes error of execution.– Marco Giovanni
I believe that is "bad" onClick in XML because it would be necessary to create a method for each button in the layout, leaving the java code immense.
– Leonardo Dias
Actually I think the "android:onClick" was implemented in android 5 that’s the only difference.
– GabrielLocalhost
@Gabriellocalhost I think the attribute
android:onClick
there has always been.– ramaral