Android Button click event in three ways

Source: Internet
Author: User

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 ("");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.