Change textview text programmatically in android

How to change text in textview on button click android.

TextView is used to hold text and basically application developer set text on textView using activity_main.xml layout file but sometimes developer needs some different task so you can change textView text easily through MainActivity.java programming file. So here is the complete step by step tutorial for Change textview text programmatically in android.

android-project-download-code-button

How to Change textview text programmatically in android.

Code for MainActivity.java file.

 package com.android_examples.com.changetextviewtextprogrammatically;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView NewText;
 Button ChangeText;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 NewText = (TextView)findViewById(R.id.textView1);
 ChangeText = (Button)findViewById(R.id.button1);
 
 ChangeText.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 //Set Text on button click via this function.
 
 NewText.setText(" Text Change successfully ");
 
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.changetextviewtextprogrammatically.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="153dp"
 android:text="THIS IS OLD TEXT"
 android:textAppearance="?android:attr/textAppearanceLarge" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="24dp"
 android:text="CLICK HERE TO CHANGE TEXTVIEW TEXT" />

</RelativeLayout>

Screenshots:

Change textview text programmatically in android

new text

Click Here To Download Change textview text programmatically in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *