android 代码设置progressBar 颜色

时间:2023-03-09 16:05:23
android 代码设置progressBar 颜色
void test() {
LinearLayout linearLayout = new LinearLayout(this);
ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
setColors(progressBar,
0xff0000FF, //bgColor blue
0xffFF0000 //progressColor red
); progressBar.setProgress(50); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_VERTICAL;
params.leftMargin = 10;
params.rightMargin = 10;
params.height = 10;
linearLayout.addView(progressBar, params);
setContentView(linearLayout);
} public void setColors(ProgressBar progressBar, int backgroundColor, int progressColor) {
//Background
ClipDrawable bgClipDrawable = new ClipDrawable(new ColorDrawable(backgroundColor), Gravity.LEFT, ClipDrawable.HORIZONTAL);
bgClipDrawable.setLevel(10000);
//Progress
ClipDrawable progressClip = new ClipDrawable(new ColorDrawable(progressColor), Gravity.LEFT, ClipDrawable.HORIZONTAL);
//Setup LayerDrawable and assign to progressBar
Drawable[] progressDrawables = {bgClipDrawable, progressClip/*second*/, progressClip};
LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);
progressLayerDrawable.setId(0, android.R.id.background);
progressLayerDrawable.setId(1, android.R.id.secondaryProgress);
progressLayerDrawable.setId(2, android.R.id.progress); progressBar.setProgressDrawable(progressLayerDrawable);
}
PS: setProgress 要放在setProgressDrawable 之后