AndroidNo Comments

default thumbnail

I have initialised the button with its id and then I have set the click listener on the button with method setOnClickListener(this). The “this” parameter indicates the our MainActivity.java class that implements the View.OnClickListener interface and also implements its method onClick(View view). The method onClick will be called when the button will be clicked. After running the code you can press the button and the log message will be printed in the Toast.

MainActivity.java

package com.example.button;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
TextView textView;

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

button=findViewById(R.id.button);
button.setOnClickListener(this);

textView=findViewById(R.id.textview);

}

@Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
Toast.makeText(this,"Welcome to android Course",Toast.LENGTH_LONG).show();
}

}
}

XML Desgin

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"

android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Web Query Solution"
android:textColor="#F10909"
android:textSize="23dp"
android:layout_margin="30dp"
android:textStyle="bold" />

<Button
android:id="@+id/button"
android:layout_width="200dp"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark"
android:text="Click me"
android:textColor="#FBFBFB" />
</LinearLayout>



</androidx.constraintlayout.widget.ConstraintLayout>

Code Result

How to add button and implement View.OnClickListener in Android Studio?

Be the first to post a comment.

Add a comment