通过code只能在Android的修改进度颜色进度、颜色、只能在、code

2023-09-12 09:18:46 作者:无人问津

我在这里读了很多的话题,但我无法找到我的答案。 我使用进度类进度。

I have read many topics here, but I can't find my answer. 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)

或类似的东西...

or something like that...

我不能使用的 XML布局,因为进度条是可定制的用户。 我会很感激,如果你能帮助我这样做。

I can't use an XML layout because the progress bar is customizable for users. I would be very grateful if you can help me doing that.

感谢您的时间,

推荐答案

当我发现帮助在这里的话题,但不记得的链接,我张贴我的全部解决方案,能很好的完成我的需要:

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);

这里是code到小数颜色值转换为十六进制:

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.