Buttons are Android widget used as a push button.The android.widget.Button is a subclass of TextView class and CompoundButton is the subclass of Button class.
Here in this Android Button Tutorial, we are going to learn handling click event of a button in Android Studio.

Step 1: Open up Android Studio Create a Project by clicking File->New->New Project and name it.Here in the tutorial, I am naming Example Button Project.
Step 2: Drag and drop Button from widget section or use this code below for button.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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.bytelogs.buttonexample.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click ME" android:id="@+id/button" android:background="@color/colorAccent" android:textColor="#ffff" android:layout_centerVertical="true" /> </RelativeLayout>
Step 3: Create OnClickListener for the button as shown below.OnClickListener handles click events of the button.
package com.bytelogs.buttonexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"You clicked Me",Toast.LENGTH_SHORT).show(); } }); } }
Leave a Comment