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


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.