Android Button Example
In Android, just use “android.widget.Button” class to display a normal button.
1.With text, using the Button class:
A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.
Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:
1.With text, using the Button class:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
/>
2.With an icon, using the ImageButton class:
<ImageButton
android:id="@+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon"
/>
3.With text and an icon, using the Button class with the android:drawableLeft attribute:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:drawableLeft="@drawable/button_icon"
/>
In this tutorial, we show you how to display a normal button, add a click listener, when user click on the button, show the toast message.
1. Add Button
Open “res/layout/main.xml” file, add a button.
File : res/layout/main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button
android:id="@+id/btnHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello"
/>
</RelativeLayout>
2. Code
package
com.learnsimply.buttonclick;
import
android.os.Bundle;
import
android.app.Activity;
import
android.view.Menu;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.Toast;
public
class
MainActivity extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button
btnClick = (Button)findViewById(R.id.btnHello);
btnClick.setOnClickListener(new
OnClickListener() {
@Override
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
Toast.makeText(MainActivity.this,
"Hello is clicked",
Toast.LENGTH_LONG).show();
}
});
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
//
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main,
menu);
return
true;
}
}
No comments:
Post a Comment