您的位置:首页 > 移动开发 > Android开发

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

2016-07-06 14:38 435 查看
在开发中,我们有时候要对控件定义使用随机的颜色,比如我做一个项目,里面有用到标签,但是我不想我的标签只有一种背景颜色框。本文就以下方法给大家介绍如何在安卓中使用随机颜色的控件。

我们通常的做法是在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);


放上一张效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息