关于layer-list在xml和代码中的用法ProgressBar

我们在使用progressbar的时候希望设定一下背景颜色和progress颜色,那我们必然会用到layer-list


第一种方法 在XML中的用法

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape android:shape="rectangle" >
            <solid android:color="#eaeaea" />
        </shape>
    </item>

     <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#54a1fd" />
            </shape>
        </clip>
    </item>

</layer-list>

看上面的item ID可以很清晰的看到前景色和背景色,这里需要说明一下前景色progress需要用clip去剪切一下,不然不会出现进度的style


第二种方法 代码中添加layer-list

Drawable[] layers = new Drawable[2];
		 Drawable background = mContext.getResources().getDrawable(R.drawable.progress_background);
		 GradientDrawable progress = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.progress_progress);
		 progress.setColor(mContext.getResources().getColor(R.color.red));
		 ClipDrawable clip = new ClipDrawable(progress,Gravity.LEFT, ClipDrawable.HORIZONTAL);
		 layers[0] = background;
		 layers[1] = clip;
		LayerDrawable layer=new LayerDrawable(layers );
		layer.setId(0, android.R.id.background);
		layer.setId(1, android.R.id.progress);
		mBbPlay.setProgressDrawable(layer);

上面两种完全可以满足基本的要求,但是我们产品UI设计中有时候会对progressbar的每个进度颜色都会有不一样的需求

那我们完全获取到前景色,然后动态的根据需求去设置颜色

LayerDrawable layerDrawable = (LayerDrawable)mBbPlay.getProgressDrawable();
		Drawable draw = layerDrawable.findDrawableByLayerId(android.R.id.progress);
		GradientDrawable progress;
		if(draw == null || !(draw instanceof ColorDrawable)){
			progress = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.progress_progress);
			draw = new ColorDrawable(progress, Gravity.LEFT, ClipDrawable.HORIZONTAL);
			layerDrawable.setDrawableByLayerId(android.R.id.progress, draw);
		}else{
			progress = ((ColorDrawable)draw).progress;
		}
		progress.setColor(mContext.getResources().getColor(R.color.red));

public class ColorDrawable extends ClipDrawable{

		public GradientDrawable progress;
		public ColorDrawable(GradientDrawable drawable, int gravity, int orientation) {
			super(drawable, gravity, orientation);
			progress = drawable;
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值