Friday, May 22, 2015

How to set TextView background color transparent programmatically in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="@android:color/white"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/animal"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample TextView..."
        android:padding="25dp"
        android:textSize="30dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Background Color Transparent"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

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

public class MainActivity extends Activity{

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

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final TextView tv = (TextView) findViewById(R.id.tv);
        Button btn = (Button) findViewById(R.id.btn);

        // Set background color red and no transparency
        // Full opaque red color
        tv.setBackgroundColor(Color.RED);

        // Set a click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Set background color transparent
                // First two character specify the opacity
                tv.setBackgroundColor(Color.parseColor("#55FF0000"));
                //tv.setBackgroundColor(Color.parseColor("#AAFF0000"));
                //tv.setBackgroundColor(Color.parseColor("#BBFF0000"));
                //tv.setBackgroundColor(Color.parseColor("#CCFF0000"));
                //tv.setBackgroundColor(Color.parseColor("#DDFF0000"));

                // Full opaque no transparency
                //tv.setBackgroundColor(Color.parseColor("#FFFF0000"));

                // Full transparent
                //tv.setBackgroundColor(Color.parseColor("#00FF0000"));
            }
        });
    }
}
More android examples