progressbar 自定义(进度)颜色(timertaskl定时器模拟)

来源:互联网 发布:常用视频制作软件 编辑:程序博客网 时间:2024/06/11 08:01

先上效果图如下:


1.提供我们progress所在的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <ProgressBar        android:id="@+id/pb_pb"        android:layout_width="match_parent"        android:layout_height="30px"        android:layout_marginLeft="20px"        android:layout_marginRight="20px"        android:max="100"        android:layout_centerInParent="true"        android:progressDrawable="@drawable/pro_10"        style="@style/Widget.AppCompat.ProgressBar.Horizontal"        /></RelativeLayout>


2.整个进度条有三种情况:0~10 显示蓝色,11~50显示红色,51~100显示橙色(可以视为我们手机电量提示格子一样,满电绿色,没电了就变成红色了)

提供三种情况下的progressbar的drawable布局中的一种(因为三者的布局其实是一样的,就是改变下所需显示的颜色)

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">    <item android:id="@android:id/background">        <shape>            <corners                android:radius="20px"/>            <solid android:color="#000"/>        </shape>    </item>    <item android:id="@android:id/progress">        <clip>            <scale android:scaleWidth="100%">                <shape>                    <corners                        android:radius="20px"/>                    <solid android:color="#2319dc"/>                </shape>            </scale>        </clip>    </item></layer-list>


3.在1中的控件progress 给 它设置我们自己写的drawable资源文件,属性为:progressDrawable 因为默认上来是0,所以给设置了个蓝色进度条以及默认的最大进度为100。


4.此时设置完默认进度条颜色后,我们需要对其进度动态的进度条色值改变(存在如下三种情况)

public Handler handler=new Handler(){    @Override    public void handleMessage(Message msg) {        super.handleMessage(msg);        if(msg.what>0&&msg.what<=10){            pb_pb.setProgressDrawable(getResources().getDrawable(R.drawable.pro_10));        }else if (msg.what>10&&msg.what<=50){            pb_pb.setProgressDrawable(getResources().getDrawable(R.drawable.pro_10_50));        }else if (msg.what>50&&msg.what<=100){            pb_pb.setProgressDrawable(getResources().getDrawable(R.drawable.pro_50_100));        }        pb_pb.setProgress(msg.what);    }};

pro_10,pro_10_50.pro_50_100,分别为进度条颜色(蓝,红,橙),你也可以根据不同的判断条件添加不同色值的drawable资源文件,我这里是三个条件三种色值。

这里的msg.what其实就是进度值(满额100,msg.what是当前的进度值)


5.最后通过定时器来模拟进度条改变带来的不同进度下的不同色值。

timer=new Timer();timerTask =new TimerTask() {    @Override    public void run() {        if(add_or_reduce){            if(count>=0&&count<100){                count++;            }else{                add_or_reduce=false;                count--;            }        }else{            if(count>0&&count<=100){                count--;            }else{                add_or_reduce=true;                count++;            }        }        handler.sendEmptyMessage(count);    }};timer.schedule(timerTask,30,30);
add_or_reduce :一个增加进度还是减少进度的判断标识;


基本的使用操作都在上面的,个别地方还需要具体解释的请留言~






原创粉丝点击