Introduction of Android Button Control
Android provides Button Control for user interface. Button control provides click event to developers. Using this developer can perform additional task.
How to define button control
Android use seperate file for layout. This file stored in android res/layout directory.
syntex :
How to define button control
Android use seperate file for layout. This file stored in android res/layout directory.
syntex :
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me" />
Above syntex define button with following properties
- android:id a unique id provided to each button.
- android:layout_width this property is used to define button width.
- android:layout_heightthis property is used to define button height.
- android:textThis property define text which is seen by users
Android provides OnClickListener for button. We need to set it manually.
How to set OnClickListener to button
- First identify your button.
Syntex : button = (Button) findViewById(R.id.button1);
- Then set event to this button control
button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { write your code } });
Example
- Make layout file(main.xml) which contains a button. If we click on button it display a message.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" /> </LinearLayout> - Then apply onclick event
public class MyAndroidAppActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnButton(); } public void addListenerOnButton() { Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(this, "Button is clicked", Toast.LENGTH_LONG).show(); } }); } } - Output :

No comments:
Post a Comment