How to Change Button Text On Button Click in Android

In the previous android code example, we explore how to get text from button when the button is clicked in android.

In this android code example, we will illustrate how to change button text on button click in android.

Copy and paste the code below and run it to see for yourself.

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="First Text"
        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 androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

    private Button changeButtonText;


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

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

        changeButtonText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeButtonText.setText("Second Text");
            }
        });

    }
}

android change 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