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

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

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
使用 Spannable 实现 TextView颜色渐变效果,你可以使用 ForegroundColorSpan 类来设置不同部分的字体颜色,并根据需要调整它们的位置和颜色值。 以下是一个示例代码,演示如何使用 Spannable 实现颜色渐变效果: ```java TextView textView = findViewById(R.id.textView); String text = "Hello World!"; Spannable spannable = new SpannableString(text); // 定义渐变色数组 int[] colors = {Color.RED, Color.GREEN, Color.BLUE}; // 定义颜色变化位置数组 float[] positions = {0f, 0.5f, 1f}; for (int i = 0; i < text.length(); i++) { // 计算当前字符的颜色 int color = interpolateColor(colors, positions, (float) i / (text.length() - 1)); // 创建 ForegroundColorSpan,并设置字体颜色 ForegroundColorSpan span = new ForegroundColorSpan(color); // 设置 span 的起始位置和结束位置 spannable.setSpan(span, i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // 将 spannable 设置给 TextView textView.setText(spannable); ``` 在这个示例中,我们首先创建了一个 SpannableString 对象,并将其初始化为需要处理的文本。然后,我们使用一个循环遍历文本中的每个字符,计算出当前字符的颜色值,然后创建一个 ForegroundColorSpan 对象,并将其应用到对应的字符上。最后,我们将处理后的 SpannableString 设置给 TextView。 在 interpolateColor 方法中,我们使用了一个插值算法来计算颜色的渐变值。你可以根据需要自定义这个方法,实现不同的颜色渐变效果。 这样,TextView 的文本就会呈现出颜色渐变的效果。你可以根据实际需求和喜好,调整渐变色数组、颜色变化位置数组以及插值算法来实现不同的颜色渐变效果。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值