Dynamically Change the Text of the Button in Android

In many Scenarios when we need a button for multiple purposes, or we need to use a same button for two or more purposes and we want the text of the button changes according to the situation so whenever some action is performed we change the text accordingly i.e. if we want to dynamically change the text of the button in android. For example, if you want to create a button to show or hide a text field and change the text accordingly i.e. If the text field is shown or enabled button is Hide/Disable button and if the text field is hidden or disabled button is to Show/Enable text field.

To achieve this goal, we need to create a button, and a text field.

Implement Button Handler onClick Event:

XML button onClick:

 

Creating Instances of EditText and Button:

To create local variables for EditText and Button by using their specific instances and pointing them through resource file R.java.

Check for the text field status if it is enabled or disabled using if else condition statements.

Change Text on Button:

If the text field is enabled and you change its state to disable, Button must display “Enable Text Field”.

If the text field is disabled and you change its state to enable, Button must display “Disable Text Field”.

 

Changing the State of the text field (Enable or Disable):

To enable the text field:

to disable the text field:

Enabled Text Field:

enabled text field
Enabled text field

 

Disabled Text Field:

Disabled text Field
Disabled text Field

Download complete source code of dynamic button text change.

XML file for EditText and Button:

You must create android onClick for capturing the click event of the button in android, and implement the onClick function in Java file of the activity.

 

Java File of Activity: