Android Button Example

In this tutorial, it shows on how to create a Button and add a click listener, when user click on the button, open an URL in your Android’s internet browser.
How it works?

1. Open “res/values/strings.xml” file, to add values.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="btn">Click Me</string>
    <string name="app_name">ESS Button</string>

</resources>
2. Open “res/layout/main.xml” file, to add button.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >


    <Button
        android:id="@+id/btnClickMe"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn" />

</LinearLayout>

3. Attach a click listener to the button. When user click on it, open mobile browser and display URL : www.erasersoftware-solution.com.www.erasersoftware-solution.com.

package ess.button.isourcecode;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ESSButtonActivity extends Activity{
    /** Called when the activity is first created. */
    Button btn;
      @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn=(Button) findViewById(R.id.btnClickMe);
        btn.setOnClickListener(new View.OnClickListener() {
                 
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent browser = new Intent(Intent.ACTION_VIEW,Uri.parse("http://i-sourcecode.blogspot.com"));
                        startActivity(browser);
                  }
            });
    }
}

4. Run the app

Programming Language: Java + XML
Programming IDE: Eclipse