1. 程式人生 > >Android TextView 使用隨機背景顏色的方法

Android TextView 使用隨機背景顏色的方法

在開發中,我們有時候要對控制元件定義使用隨機的顏色,比如我做一個專案,裡面有用到標籤,但是我不想我的標籤只有一種背景顏色框。本文就以下方法給大家介紹如何在安卓中使用隨機顏色的控制元件。
我們通常的做法是在xml檔案中對控制元件寫一個background的資原始檔。例如:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_topic_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:layout_marginLeft="12dp" android:layout_marginTop="10dp" android:background="@drawable/bg_textview_green_stroke_drawable_no_selec" android:textColor="@color/color_black_232323" android:textSize="12.5dp" />

然後在資原始檔中定義相關的顏色屬性設定:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/color_white_pure" /> <stroke android:width="1dp" android:color="#61e0fe" /> <padding android:bottom="6dp" android:left="10dp" android:right="10dp"
android:top="6dp" />
<corners android:radius="25dp" /> </shape>

其實相當於是寫死的,所以我們可以從java程式碼中開搞:

GradientDrawable bgShape = (GradientDrawable)textview.getBackground();
//                    bgShape.setColor(Color.BLACK);
bgShape.setStroke(1, Color.parseColor(ColorUtil.getRandomColor()));

getRandomColor是我自己封裝的一個隨機生成顏色的類,這樣我們就可以對自己的控制元件使用隨機生成顏色了。其實還可以設定其他的屬性:

 // prepare
    int strokeWidth = 5; // 3px not dp
    int roundRadius = 15; // 8px not dp
    int strokeColor = Color.parseColor("#2E3135");
    int fillColor = Color.parseColor("#DFDFE0");

   bgShape.setColor(fillColor);
   bgShape.setCornerRadius(roundRadius);

放上一張效果圖:
這裡寫圖片描述