Android 中的 ProgressBar拥有很多样式,本文针对自定义进度条背景及进度样式设置抛砖引玉。先看看效果
先定义一个带progressBar的布局,代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 RelativeLayout rl = new RelativeLayout(this);
ProgressBar mProgressBar = new ProgressBar(this,null,android.R.drawable.progress_horizontal);// 下载进度条
RelativeLayout.LayoutParams mProgressBarParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 20);
mProgressBarParams.setMargins(10, 10, 10, 10);
mProgressBar.setLayoutParams(mProgressBarParams);
mProgressBarParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mProgressBarParams.addRule(RelativeLayout.CENTER_VERTICAL);
// BeanUtils.setFieldValue(mProgressBar, "mOnlyIndeterminate", new Boolean(false));
mProgressBar.setIndeterminate(false);
// mProgressBar.setProgressDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
** mProgressBar.setProgressDrawable(getProgressBarLayerDrawable());**
// mProgressBar.setIndeterminateDrawable(getResources().getDrawable(android.R.drawable.progress_indeterminate_horizontal));
mProgressBar.setMax(100);
mProgressBar.setBackgroundColor(Color.argb(10, 11, 11, 11));
rl.addView(mProgressBar);
setContentView(rl);
mProgressBar.setProgress(20);
其中最重要的是getProgressBarLayerDrawable()方法,它定义了一个背景的drawable,代码如下:1
2
3
4
5
6
7
8
9public static LayerDrawable getProgressBarLayerDrawable() {
GradientDrawable shapeDrawable = new GradientDrawable();
shapeDrawable.setCornerRadius(0);
shapeDrawable.setColor(Color.RED);
ClipDrawable clipDrawable = new ClipDrawable(shapeDrawable, ClipDrawable.VERTICAL, ClipDrawable.HORIZONTAL);
ClipDrawable[] drawables = new ClipDrawable[] { clipDrawable };
LayerDrawable layerDrawable = new LayerDrawable(drawables);
return layerDrawable;
}
LayerDrawable是一个层叠图形对象,可以理解为其返回的对象为一个个图层合成的图形对象,上面代码通过合成一个GradientDrawable对象来得到一个LayerDrawable,只是一个例子,在实际实用中完全可以使用其他形式的Drawable(及其子类)的对象数组来创建不同样式的层叠图形,然后将其作为背景drawable设置到进度条中就可以了。