In this tutorial we will learn about how to implement a button, how to set onClick listener for button,show a toast when button is clicked and their example .
Android provides another supporting widget , i.e. android.widget.Button which is used to click to perform an action or event . Button is an user interface i.e. the user can tap to perform an event/action .
Button provides the onClick() method which is used if button get clicked it will listen and call the method or perform an action.
1. Create a New Project :
Lets we start with a new project in Android Studio from File New Project ⇒
select Empty Activity and go through it.
2. Implement button in android xml layout :
Add Button to your XML Layout file i.e. activity_main.xml to implement clickListener to display it for better user experience or just add the following code to activity_main.xml file .
<Button
android:background="@android:color/holo_red_light"
android:id="@+id/btn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
activity_main.xml :
<?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">
<Button
android:background="@android:color/holo_red_light"
android:id="@+id/btn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
</RelativeLayout>
3. Implement onClickListener of Button :
Now set onClickListener of Button to perform an action or event, like toast message in MainActivity.java file .
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Hello world",Toast.LENGTH_SHORT).show();
}
});
MainActivity.java :
package net.technxt;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
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 {
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Hello world",Toast.LENGTH_SHORT).show();
}
});
}
}
Now run the project/app in android device or any Emulator to add button in android app.