Set TextView text color in android programmatically

How to change text color in android on button click.

On android application there are multiple ways to change TextView text color using layout file and programming file. Developer can change text using both methods but defining color using activity_main.xml file is static method and declaring text color using MainActivity.java programming file is the dynamic method. So here is the complete step by step tutorial for How to Set TextView text color in android programmatically.

android-project-download-code-button

List of all colors that can be choose by setTextColor() function.

android color list

Note: You can also set custom color with #color codes using this simple method.

textview.setTextColor(Color.parseColor(“#ColorCode”));

Set TextView text color in android programmatically.

Code for MainActivity.java file.

package com.android_examples.com.changetextcolor;

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

public class MainActivity extends Activity {
 
 TextView TxtChange;
 Button BtnColor;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 TxtChange = (TextView)findViewById(R.id.textView1);
 BtnColor = (Button)findViewById(R.id.button1);
 
 BtnColor.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 TxtChange.setTextColor(Color.GREEN);
 
 }
 });
 
 }
}

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.changetextcolor.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO CHANGE TEXT COLOR" />

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_above="@+id/button1"
 android:layout_centerHorizontal="true"
 android:layout_marginBottom="34dp"
 android:text="THIS IS TEXT"
 android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Screenshot:

Set TextView text color in android programmatically

color changed successfully

Click Here To Download Set TextView text color in android programmatically project.

Leave a Reply

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