作者:手机用户2602927935 | 来源:互联网 | 2023-05-18 06:01
在开发中,我们有时候要对控件定义使用随机的颜色,比如我做一个项目,里面有用到标签,但是我不想我的标签只有一种背景颜色框。本文就以下方法给大家介绍如何在安卓中使用随机颜色的控件。我们通常的做法
在开发中,我们有时候要对控件定义使用随机的颜色,比如我做一个项目,里面有用到标签,但是我不想我的标签只有一种背景颜色框。本文就以下方法给大家介绍如何在安卓中使用随机颜色的控件。
我们通常的做法是在xml文件中对控件写一个background的资源文件。例如:
"http://schemas.android.com/apk/res/android"
android:id="@+id/tv_topic_item"
android:layout_hljs-string">"wrap_content"
android:layout_hljs-string">"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" />
然后在资源文件中定义相关的颜色属性设置:
<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是我自己封装的一个随机生成颜色的类,这样我们就可以对自己的控件使用随机生成颜色了。其实还可以设置其他的属性:
int strokeWidth = 5;
int roundRadius = 15;
int strokeColor = Color.parseColor("#2E3135");
int fillColor = Color.parseColor("#DFDFE0");
bgShape.setColor(fillColor);
bgShape.setCornerRadius(roundRadius);
放上一张效果图:
![这里写图片描述](https://img1.php1.cn/3cd4a/24de0/696/a4638643217a2a77.jpeg)