How to Get Button Text When Button is Clicked in Android

You can get a button text in android when the button is clicked by using the Button class getText()method which return a sequence of char that can be converted to string with toString()method.

The android code below illustrates a simple example on how to get button text when the button is clicked in android.

activity_main_xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="My Button"
        android:textColor="@color/colorWhite"
        android:textStyle="bold"
        android:textSize="15sp"/>

</androidx.appcompat.widget.LinearLayoutCompat>

MainActivity.java

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private Button getButtonText;


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

        getButtonText = (Button)findViewById(R.id.button_text);

        getButtonText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Result: "+ getButtonText.getText().toString(),Toast.LENGTH_LONG).show();
            }
        });

    }
}

android get button text

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment