Android简单实现一个颜色渐变的ProgressBar的方法

时间:2021-05-19

今天看一个教程,看到一个颜色渐变的ProgressBar,觉得有点意思,所以记录一番。
下面这个是效果图

颜色渐变的ProgressBar

看到效果图可能会给人一种使用了高端技术的感觉,其实这个没有那么高深,我们只是简单改变了ProgressBar的样式即可实现,下面说说实现方式。

首先我们简单分析一下:

1 . 上面的样式只是实现了颜色渐变,但它旋转和呈现的方式仍然是一个圆形的ProgressBar。

2 . 这个ProgressBar实现了颜色渐变,我们就需要用到gradient,这个也比较简单,只要我们配置开始,中间,结束颜色即可实现
明白了上面两点我们就开始写代码。

首先,我们实现上面的布局,背景灰色,一个ProgressBar居中,一个TextView位于ProgressBar下方。
代码如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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="cn.codekong.androidloading.MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#de262a3b"> <ProgressBar android:id="@+id/loading" android:layout_width="60dp" android:layout_height="60dp" android:layout_centerInParent="true" android:indeterminate="false"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/loading" android:text="加载中" android:textColor="#ffffff" android:textSize="20sp" android:layout_centerHorizontal="true"/> </RelativeLayout></RelativeLayout>

上面其他代码都很好理解,只有ProgressBar有一个 indeterminate 属相需要解释一下:

一般的ProgressBar都是用于显示加载进度,如果我们直到当前的具体进度,那个这个属性要设置为true,并设置正确的进度,如果我们也不知道正确的进度,则设置为false。

布局设置好了,下一步就是设置ProgressBar的渐变样式,这里我们需要自定义一个Drawable。

自定义的Drawable代码如下:

<?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="1080.0"> <shape android:innerRadiusRatio="3" android:shape="ring" android:thicknessRatio="10" android:useLevel="false"> <gradient android:centerColor="#FFDC35" android:centerY="0.50" android:endColor="#CE0000" android:startColor="#FFFFFF" android:type="sweep"/> </shape></rotate>

下面解释一下上面的代码:

外层的 rotate 表明这是一个旋转的动画,并且该规定了开始角度和结束角度,还有旋转中心为圆心

内层的shape定义了形状为一个环(ring),其中有三个属性:

<1> innerRadiusRatio 为外环半径和内径的比值,比如外环半径为30,内环半径为10,则比值为3

<2> thicknessRatio 为外环半径与环的厚度的比值

<3> useLevel 如果为true,则可以在LevelListDrawable中使用

接下来的 gradient 定义了渐变效果,规定了开始结束的颜色,还规定渐变方式为扫描渐变

最后一步,我们通过一个ProgressBar的属性给他设置我们上面定义的样式:

android:indeterminateDrawable="@drawable/loading_drawable"

经过上面的步骤我们就实现了一个简单的渐变的ProgressBar,是不是超级简单,希望可以帮助到需要的人。

源码地址: https://github.com/codekongs/Android-Learning/tree/master/AndroidLoading

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章