create Random Color TextView - Android java.util

Android examples for java.util:Random

Description

create Random Color TextView

Demo Code


//package com.java2s;
import java.util.Random;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class Main {

    public static TextView createRandomColorTextView(Context context) {
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);/*from   ww w.j  a va2 s. c om*/
        tv.setTextColor(Color.WHITE);
        int padding = 6;
        tv.setPadding(padding, padding, padding, padding);
        tv.setBackgroundDrawable(createRandomColorSelector());
        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), ((TextView) v).getText(), 0)
                        .show();
            }
        });
        return tv;
    }

    private static Drawable createRandomColorSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();

        int[] pressState = { android.R.attr.state_pressed,
                android.R.attr.state_enabled };
        int[] normalState = {};

        Drawable pressDrawable = createRandomColorDrawable();
        Drawable normalDrawable = createRandomColorDrawable();

        stateListDrawable.addState(pressState, pressDrawable); 
        stateListDrawable.addState(normalState, normalDrawable);

        return stateListDrawable;
    }

    private static Drawable createRandomColorDrawable() {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setCornerRadius(5);
        drawable.setColor(createRandomColor());
        return drawable;
    }

    public static int createRandomColor() {
        Random random = new Random();
        int red = 50 + random.nextInt(151); 
        int green = 50 + random.nextInt(151); 
        int blue = 50 + random.nextInt(151); 
        int color = Color.rgb(red, green, blue);
        return color;
    }
}

Related Tutorials