Can anybody tell how to add a button in android?
Asked
Active
Viewed 5.9k times
3 Answers
16
Check this Android Button tutorial; this simple example creates a Close Button.
All you need to do is:
1.Add Button widget to your Layout
<Button android:id="@+id/close"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/title_close" />
2.Attach a setOnClickListener method to the button instance:
protected void onCreate(Bundle savedInstanceState) {
this.setContentView(R.layout.layoutxml);
this.closeButton = (Button)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}

systempuntoout
- 71,966
- 47
- 171
- 241
-
hi, is it possible to add a button without declaring it in the layout xml file? – poeschlorn May 11 '10 at 12:34
-
Check here: http://stackoverflow.com/questions/1851633/how-to-add-button-dynamically-in-android – droidgren Jul 02 '11 at 21:44
9
Dynamic:
Button btn= new Button(this);
btn.settext("Submit");
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
//your write code
}
});

AnilPatel
- 2,356
- 1
- 24
- 40
1
According to official documentation of Buttons provided by Android.
You can first create Button in your .xml
file.
Button.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />
And then cast your button with Button Class and set ClickListener.
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
For further detail you can visit this link

Rehan Sarwar
- 994
- 8
- 20