Android UI How to - Create a Button








The basic button class in Android is android.widget.Button. You use it to handle click events.

Example

The following code shows how to add a button to activity and add click action handler.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*ww  w  .ja va  2s.  com*/
    <Button android:id="@+id/button1"
        android:text="My Button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java code

package com.java2s.app;
//from   w ww . j  a  v a  2s  .  co  m
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = (Button) this.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.java2s.com"));
                startActivity(intent);
            }
        });
    }

}
null