Android Button click event in three ways
1. in XML
>
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent" >
Android: layout_height = "match_parent"
Android: orientation = "vertical" >
Tools: context = "$ {relativePackage}. $ {activityClass}">
Android: id = "@ + id/edit_text" >
Android: layout_width = "wrap_content" >
Android: layout_height = "wrap_content"
Android: text = "@ string/hello_world1"/> >
Android: id = "@ + id/clear_button"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "click to clear input"/>
//---------------------------------------------------------
In. java
Package com. example. myandroid;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. Menu;
Import android. view. MenuItem;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. EditText;
Public class MainActivityextends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Final EditText editText = (EditText) findViewById (R. id. edit_text); // obtain the control
Button button = (Button) findViewById (R. id. clear_button );
Button. setOnClickListener (new Button. OnClickListener () {// create a listener
Public void onClick (View v ){
EditText. setText ("");
}
});
};
}
2. xml does not change in. java
Button. setOnClickListener (listener );
Button. OnClickListener listener = new Button. OnClickListener () {// create a listener object
Public void onClick (View v ){
EditText. setText ("");
}
};
3. Modify the button in xml
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/button_send"
Android: onClick = "sendMessage"/>
. Java File
Public void sendMessage (View view ){
EditText. setText ("");
}