Button Controls in Android Application
In this article I am going to
explain how to create and use a button control in an Android Application. I am
going to create three button (New, Save, Print), when a user clicked on the
button the toast message will be
display.
Start a New Project, named ButtonDemo.
Open res/values/strings.xml
and add a string in the resources tag.
<string
name="onClick">onClick</string>
Open res/layout/main.xml
and add three button as shown below:
<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/btnNew"
android:layout_width="150px"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button android:id="@+id/btnSave"
android:layout_width="150px"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button android:id="@+id/btnPrint"
android:layout_width="150px"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
</LinearLayout>
Open a activity file and add the following code in that activity:
import
android.app.Activity;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
import
android.widget.Toast;
public
class FormActivity
extends Activity {
@Override
public
void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnNew=(Button)findViewById(R.id.btnNew);
Button btnSave=(Button)findViewById(R.id.btnSave);
Button btnPrint=(Button)findViewById(R.id.btnPrint);
btnNew.setText("New");
btnSave.setText("Save");
btnPrint.setText("Print");
}
public
void
onClick(View v) {
switch(v.getId())
{
case R.id.btnNew:
Toast.makeText(FormActivity.this,
"You clicked
New",
Toast.LENGTH_SHORT).show();
break;
case R.id.btnSave:
Toast.makeText(FormActivity.this,
"You clicked
Save",Toast.LENGTH_SHORT).show();
break;
case R.id.btnPrint:
Toast.makeText(FormActivity.this,
"You clicked
Print",Toast.LENGTH_LONG).show();
break;
}
}
}
Run the application
Your output should look like below:
You can click on button, it will
display a toast message.