Android Button with Listener Example || How to add Button in Android || How to set Button in Android || Working with Button in Android - Android Tutorial World

Latest

Welcome to Android Tutorial World Blog, Here you can find all type of post or tutorial related to andorid app development in details.

Wednesday, September 11, 2019

Android Button with Listener Example || How to add Button in Android || How to set Button in Android || Working with Button in Android

Android Button With Listener Example


This is Android Button Tutorial with listener. We will show you how to add button on empty activity
with listener and provide you all images with source code of this tutorial

Follow all step :-

Step 1. Open Android Studio and create new project in android studio

Step 2. Fill Application name( Your App Name ), Package name etc.

Step 3. After Build new project open activity_main.xml and write the Button code and see the below

Text Code :-
<Relativelayout android:layout_height="match_parent" 
      android:layout_width="match_parent"
      tools:context=".MainActivity"
      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">

    <Button
          android:id="@+id/btn"   
          android:layout_centerinparent="true" 
          android:layout_height="wrap_content"
          android:layout_width="wrap_content" 
          android:text="Button">

</Relativelayout>
Note:-Write the Button id according to your need like id=@+id/write any but remember it. Because when you use listener you need to find the button by its own id.

If you want to use multiple Button then you need to provide different IDs to all your Buttons.


Step 4. Now Open MainActivity.java File and write the code for use button with the listener

Text Code:-
package com.akshayarora.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = (Button)findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Button clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Note :- In findViewById(R.id.btn); set the button id.

If you use multiple Buttons you need to provide a different id. Because id provides an identity to a Button / Widget So you need to provide a different id.

Now Run and see the output




Enjoy!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.