微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于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,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;
		}
	}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。