热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

AndroidTextView使用随机背景颜色的方法

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

在开发中,我们有时候要对控件定义使用随机的颜色,比如我做一个项目,里面有用到标签,但是我不想我的标签只有一种背景颜色框。本文就以下方法给大家介绍如何在安卓中使用随机颜色的控件。
我们通常的做法是在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是我自己封装的一个随机生成颜色的类,这样我们就可以对自己的控件使用随机生成颜色了。其实还可以设置其他的属性:

 // 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);

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


推荐阅读
author-avatar
手机用户2602927935
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有