Home » Android

Android Button Example Code



In this tutorial, we are going to learn about button in android i.e. How to display a normal button and to add a click listener, when user clicks on the button, an URL opens a webpage?
Submitted by Shamikh Faraz, on April 28, 2018

1) XML File: activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.faraz.button_example.MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to includehelp.com"
        tools:layout_editor_absoluteX="110dp"
        tools:layout_editor_absoluteY="215dp" />

</android.support.constraint.ConstraintLayout>

2) File: MainActivity.java

package com.example.faraz.button_example;

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

public class MainActivity extends Activity {

    Button button;

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

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent browserIntent =
                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.includehelp.com"));
                startActivity(browserIntent);

            }

        });

    }

}

Output

After executing your code on your virtual device, you get following output. As you click on the button you will be directed to includehelp.com page.

Output - Android Button Example Code 1
Output - Android Button Example Code 2






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.