23

Can anybody tell how to add a button in android?

Arthulia
  • 190
  • 13
vijay
  • 229
  • 1
  • 2
  • 7
  • possible duplicate of [How can I dynamically create a button in Android?](http://stackoverflow.com/questions/3011092/how-can-i-dynamically-create-a-button-in-android) – tzot Nov 09 '11 at 07:35

3 Answers3

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
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