Android TextView 使用随机背景颜色的方法

来源:互联网 发布:sg是什么软件 编辑:程序博客网 时间:2024/04/28 18:13

在开发中,我们有时候要对控件定义使用随机的颜色,比如我做一个项目,里面有用到标签,但是我不想我的标签只有一种背景颜色框。本文就以下方法给大家介绍如何在安卓中使用随机颜色的控件。
我们通常的做法是在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);

放上一张效果图:
这里写图片描述

1 0