Create textview with background color filled using programming coding on button click.
TextView background color is by default set as invisible means there are no background color specified so textview display its activity screen background color as its own. But developer can change textView background color easily on button click event. So here is the complete step by step tutorial for Set textview background color android programmatically.
How to Set textview background color android programmatically.
List of colors that can apply programmatically.
Code for MainActivity.java file.
package com.textviewbackgroundcolor_android_examples.com;
import android.annotation.SuppressLint;
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 txtview;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
txtview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceAsColor") @Override
public void onClick(View v) {
txtview.setBackgroundColor(Color.RED);
}
});
}
}
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.textviewbackgroundcolor_android_examples.com.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="THIS IS TEXTVIEW WIDGET IN ANDROID APPLICATION. " android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center" /> <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 set textview background color programmatically" /> </RelativeLayout>
Screenshot: