本文来自网易云社区

作者:孙有军

产品中有一个需求,要求TextView的文字有一个高亮的效果,高亮的同时有跑马灯效果!

本来想在网上找一个现成的用用,比如Facebook出的Shimmer,还有很多,但是都感觉代码太多,因此撸了一个简单版的,talk is cheap,show me you code。

实现

我们知道TextView的文字的颜色是由Paint根据Color控制的,我们可以设置Paint的Shader来实现该效果,这样在TextView绘制的时候Paint会从对应的Shader获取color来实现绘制。既然TextView要高亮,说明文字颜色不一致,这里我们可以设置一线性渐变shader,这样就可以设置不同部分的文字不同颜色。至于跑马灯那就一直水平改变Shader就可以实现。

属性定义

虽然是简单的,还是要通用,比如颜色可以自定义,方向可以设置,是否自动开始,这里我们先定义几个属性:

<declare-styleable name="ShimmerTextView">
    <attr name="auto_start" format="boolean"></attr>
    <attr name="start_color" format="reference|color"></attr>
    <attr name="end_color" format="reference|color"></attr>
    <attr name="direction" format="boolean"></attr></declare-styleable>

这里我们分别控制了是否自动开始,开始颜色,结束颜色,方向

代码实现

这里我们实现一个继承自AppCompatTextView的自定义TextView。

public class ShimmerTextView extends android.support.v7.widget.AppCompatTextView {

    public static final int OFFSET_ONE_TIME = 15;

    private Paint paint;

    private LinearGradient gradient;

    private Matrix matrix;

    private int w, h;

    private boolean horizontal;

    private boolean autoStart;

    private int startColor;

    private int endColor;

    private static final int DEFAULT_START_COLOR = 0xFFFF50ED;

    private static final int DEFAULT_END_COLOR = 0xFF3455FF;

    private float offset = 0;

    private ValueAnimator animator;

    public ShimmerTextView(Context context) {
        super(context);
        init(context, null);
    }     public ShimmerTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }     public ShimmerTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }     private void init(Context context, AttributeSet attrs) {
        paint = getPaint();
        matrix = new Matrix();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShimmerTextView);
        autoStart = array.getBoolean(R.styleable.ShimmerTextView_auto_start, false);
        startColor = array.getColor(R.styleable.ShimmerTextView_start_color, DEFAULT_START_COLOR);
        endColor = array.getColor(R.styleable.ShimmerTextView_end_color, DEFAULT_END_COLOR);
        horizontal = array.getBoolean(R.styleable.ShimmerTextView_direction, true);
        array.recycle();
    }     @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.w = w;
        this.h = h;
        setGradient();
    }     private void setGradient() {
        if (horizontal) {
            gradient = new LinearGradient(0, 0, w, 0, new int[]{startColor, endColor, startColor}, new float[]{0, 
                    0.5f, 1.0f}, Shader.TileMode.CLAMP);
        } else {
            gradient = new LinearGradient(0, 0, 0, h, new int[]{startColor, endColor, startColor}, new float[]{0, 
                    0.5f, 1.0f}, Shader.TileMode.CLAMP);
        }
        paint.setShader(gradient);
        invalidate();
        if (autoStart) {
            play();
        }
    }     public void play() {
        ValueAnimator animator = getAnimator();
        if (animator.isRunning()) {
            return;
        }
        animator.start();
    }     @NonNull
    private ValueAnimator getAnimator() {
        if (animator == null) {
            animator = ValueAnimator.ofFloat(0.0f, 1.0f);
            animator.setDuration(500);
            animator.setRepeatCount(ValueAnimator.INFINITE);
            animator.setRepeatMode(ValueAnimator.RESTART);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    offset += OFFSET_ONE_TIME;
                    if (horizontal) {
                        if (offset > w) {
                            offset = -w;
                        }
                    } else {
                        if (offset > h) {
                            offset -= h;
                        }
                    }
                    invalidate();
                }
            });
        }
        return animator;
    }     public void stop() {
        if (animator != null) {
            animator.cancel();
        }
    }     public void reset() {
        if (animator != null) {
            animator.cancel();
            animator = null;
        }
    }     @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        reset();
    }     @Override
    protected void onDraw(Canvas canvas) {
        matrix.setTranslate(offset, 0);
        gradient.setLocalMatrix(matrix);
        super.onDraw(canvas);
    }
}

上面的代码主要先解析了自定义属性,之后设置了一个线性渐变来改变文字的颜色,之后采用了ValueAnimator来水平移动线性渐变,同时重新绘制内容。

ValueAnimator 我们设置了一直重复动画,ValueAnimator就是一个数值发生器,其实可以用Handler与post来实现相同的效果。只要按一定速率改变线性渐变就可以

  • 需要注意的是当距离大于整个View的宽度或者高度时,需要重新开始

效果

最后我们在界面中使用该控件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.demo.example.activity.ShimmerViewActivity">     <com.demo.example.widget.ShimmerTextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginBottom="8dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:layout_marginTop="8dp"        android:gravity="center"        android:text="我爱北京天安门"        android:textSize="25sp"        app:auto_start="true"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintHorizontal_bias="0.502"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintVertical_bias="0.148"/> </android.support.constraint.ConstraintLayout>

在Activity中设置该控件,运行效果。

网易云免费体验馆,0成本体验20+款云产品!

更多网易研发、产品、运营经验分享请访问网易云社区

相关文章:
【推荐】 abtest-system后台系统设计与搭建
【推荐】 责任链模式的使用-Netty ChannelPipeline和Mina IoFilterChain分析
【推荐】 4月第3周业务风控关注 | 文化部再次审查直播和游戏产品,已下架4939款直播应用

ShimmerTextView的更多相关文章

  1. 更强的微光闪烁效果--第三方开源--Shimmer-android

    Shimmer-android在github上的项目主页是:https://github.com/RomainPiel/Shimmer-android Shimmer-android干脆在Androi ...

  2. Android Tools 开发工具库开源项目总结

    在Android开发中,我们不免会遇到使用一些工具库来简化我们的工具代码的编写,以下是本人之前star的开源项目,供大家参考: 一.android_testsuite 项目地址:https://git ...

  3. 模拟QQ分组(具有伸缩功能) (添加开源框架的光闪烁效果)SimpleExpandableListAdapter 适配器的用法,并且可添加组及其组内数据。

    package com.lixu.qqfenzu; import java.util.ArrayList; import java.util.HashMap; import java.util.Lis ...

  4. 认识一下Kotlin语言,Android平台的Swift

    今天在CSDN首页偶然看到一个贴子JetBrains正式公布Kotlin 1.0:JVM和Android上更好用的语言 看完后,感觉Kotlin语法非常简洁,有一系列动态语言的特点,Lambda表达式 ...

  5. LinearGradient线型渐变效果

    public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, TileM ...

随机推荐

  1. Hadoop-2.2.0中文文档—— Common - 超级用户模拟别的用户

    简单介绍 此文档描写叙述了一个超级用户怎样在安全的方式下以还有一用户的名义提交作业或訪问hdfs. Use Case 下一部分描写叙述的的代码演示样例对此用户用例是可用的. 一个username为's ...

  2. LSF作业管理系统使用方法

    查看LSF计算节点列表bhosts # bhosts HOST_NAME STATUS JL/U MAX NJOBS RUN SSUSP USUSP RSV fat01 ok - 16 0 0 0 0 ...

  3. Loj#572. 「LibreOJ Round #11」Misaka Network 与求和

    题目 有生之年我竟然能\(A\) 这个题求的是这个 \[\sum_{i=1}^n\sum_{j=1}^nf(gcd(i,j))^k\] \(f(i)\)定义为\(i\)的次大质因子,其中\(f(p)= ...

  4. UVA11987 【Almost Union-Find】

    这是一道神奇的题目,我调了大概一天多吧 首先hack一下翻译,操作3并没有要求查询后从其所在集合里删除该元素 于是我们来看一下这三个操作 第一个合并属于并查集的常规操作 第三个操作加权并查集也是可以解 ...

  5. 从零一起学Spring Boot之LayIM项目长成记(一) 初见 Spring Boot

    项目背景 之前写过LayIM的.NET版后端实现,后来又写过一版Java的.当时用的是servlet,websocket和jdbc.虽然时间过去很久了,但是仍有些同学在关注.偶然间我听说了Spring ...

  6. spring注入bean的三种方法

    在Spring的世界中, 我们通常会利用bean config file 或者 annotation注解方式来配置bean. 在第一种利用bean config file(spring xml)方式中 ...

  7. PAT——1013. 数素数

    令Pi表示第i个素数.现任给两个正整数M <= N <= 104,请输出PM到PN的所有素数. 输入格式: 输入在一行中给出M和N,其间以空格分隔. 输出格式: 输出从PM到PN的所有素数 ...

  8. Redis与Python进行交互

    安装包 安装Redis的有3种方式https://github.com/andymccurdy/redis-py 第一种:进⼊虚拟环境,联⽹安装包redis pip install redis 第二种 ...

  9. ThinkPHP5.0框架事务处理操作简单示例

    本文介绍ThinkPHP5.0框架事务处理操作,结合实例形式分析了ThinkPHP5针对删除操作的事务处理相关操作技巧,可以加深对ThinkPHP源码的理解,需要的朋友可以参考下 事务的调用在mysq ...

  10. Dubbo client 启动报错:No provider available for the service use dubbo version 2.5.3

    1.异常 java.lang.IllegalStateException: Failed to check the status of the service org.ko.server.servic ...