问题描述
我有一个使用 ProgressBar 类的 progressBar.
I have a progressBar using the ProgressBar class.
就这样做:
progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
我需要更改那个颜色,使用输入值,如下所示:
I need to change the color of that one, using input value like so:
int color = "red in RGB value".progressBar.setColor(color)
或者类似的东西...
我无法使用 XML 布局,因为可以为用户自定义进度条.
I can't use an XML layout because the progress bar is customizable for users.
推荐答案
由于我在此处找到了有关某个主题的帮助但不记得链接,因此我将发布非常适合我的需求的完整解决方案:
As I found help on a topic here but can't remember the link, I'm posting my full solution which works great for my needs:
// Draw a simple progressBar from xml
progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
// Convert the color (Decimal value) to HEX value: (e.g: #4b96a0)
String color = colorDecToHex(75, 150, 160);
// Define a shape with rounded corners
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
ShapeDrawable pgDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
// Sets the progressBar color
pgDrawable.getPaint().setColor(Color.parseColor(color));
// Adds the drawable to your progressBar
ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
progressBar.setProgressDrawable(progress);
// Sets a background to have the 3D effect
progressBar.setBackgroundDrawable(Utils.getActivity().getResources()
.getDrawable(android.R.drawable.progress_horizontal));
// Adds your progressBar to your layout
contentLayout.addView(progressBar);
这里是将 DECIMAL 颜色值转换为 HEXADECIMAL 的代码:
And here is the code to convert DECIMAL color values to HEXADECIMAL:
public static String colorDecToHex(int p_red, int p_green, int p_blue)
{
String red = Integer.toHexString(p_red);
String green = Integer.toHexString(p_green);
String blue = Integer.toHexString(p_blue);
if (red.length() == 1)
{
red = "0" + red;
}
if (green.length() == 1)
{
green = "0" + green;
}
if (blue.length() == 1)
{
blue = "0" + blue;
}
String colorHex = "#" + red + green + blue;
return colorHex;
}
我认为最后一种方法不是那么干净,但效果很好.
I think the last method is not that clean but it works well.
希望这对你有帮助,在这个进度条上浪费了太多时间.
Hope this well help, too much time wasted on this progressbar.
这篇关于在 Android 中通过 CODE ONLY 更改进度条颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!