programing

Android에서만 코드를 통해 진행률 표시 줄 색상 변경

projobs 2021. 1. 17. 10:21
반응형

Android에서만 코드를 통해 진행률 표시 줄 색상 변경


ProgressBar 클래스를 사용하는 progressBar가 있습니다.

그냥 이렇게 :

progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

다음과 같이 입력 값을 사용하여 해당 색상을 변경해야합니다.

int color = "red in RGB value".progressBar.setColor(color)

또는 그런 것 ...

진행률 표시 줄은 사용자가 사용자 지정할 수 있기 때문에 XML 레이아웃을 사용할 수 없습니다 .


이렇게하면 코딩을 많이 할 필요가 없습니다. :)

ProgressBar spinner = new android.widget.ProgressBar(
            context,
            null,
            android.R.attr.progressBarStyle);

spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000,android.graphics.PorterDuff.Mode.MULTIPLY);

배경색과 진행률 표시 줄을 다른 색으로 칠해야하는 경우.

progress_drawable.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="@color/white" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="@color/green" />
            </shape>
        </clip>
    </item>
</layer-list>

프로그래밍 방식으로 레이어 목록 항목을 분해하고 개별적으로 색조를 지정할 수 있습니다.

LayerDrawable progressBarDrawable = (LayerDrawable) progressBar.getProgressDrawable();
Drawable backgroundDrawable = progressBarDrawable.getDrawable(0);
Drawable progressDrawable = progressBarDrawable.getDrawable(1);

backgroundDrawable.setColorFilter(ContextCompat.getColor(this.getContext(), R.color.white), PorterDuff.Mode.SRC_IN);
progressDrawable.setColorFilter(ContextCompat.getColor(this.getContext(), R.color.red), PorterDuff.Mode.SRC_IN);

여기에서 주제에 대한 도움말을 찾았지만 링크를 기억할 수 없기 때문에 내 필요에 맞는 전체 솔루션을 게시하고 있습니다.

    // 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로 변환하는 코드입니다.

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

마지막 방법은 그렇게 깨끗하지는 않지만 잘 작동한다고 생각합니다.

이 진행률 표시 줄에 너무 많은 시간이 낭비되기를 바랍니다.


최신 정보

최신 버전의 Android (21 개 작동)에서는를 사용하여 프로 그래 매틱 방식으로 진행률 표시 줄의 색상을 변경할 수 있습니다 setProgressTintList.

빨간색으로 설정하려면 다음을 사용하십시오.

//bar is a ProgressBar
bar.setProgressTintList(ColorStateList.valueOf(Color.RED));

진행률 표시 줄 드로어 블에서 색상 필터를 설정하여 진행률 표시 줄을 색상화할 수 있습니다.

Drawable drawable = progressBar.getProgressDrawable();
drawable.setColorFilter(new LightingColorFilter(0xFF000000, customColorInt));

이것은 AppCompat와 함께 작동합니다. DrawableCompat.setTint (progressBar.getProgressDrawable (), tintColor);


프로그래밍 방식으로 진행률 표시 줄의 색상을 변경하려면이 코드를 복사하여 100 % 작동합니다.

 mainProgressBar.getIndeterminateDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);   

progressbar.setIndeterminateTintList(ColorStateList.valueOf(Color.RED));

API 21 이상에서만 작동합니다.


나는 drawable 의해 xml의 기본 색상지정 했습니다 .

프로그래밍 방식으로 변경했습니다.

activity_splasg.xml :

<ProgressBar
       android:id="@+id/splashProgressBar"
       android:progressDrawable="@drawable/splash_progress_drawable"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:max="100"
       android:progress="50"
       style="?android:attr/progressBarStyleHorizontal"
       android:layout_alignParentBottom="true" />

splash_progress_drawable.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>
            <solid
                android:color="@android:color/transparent" />
        </shape>
    </item>

    <item
        android:id="@android:id/progress">
        <clip>
            <shape>
                <solid
                    android:color="#e5c771" />
            </shape>
        </clip>
    </item>

</layer-list>

Now How to change ProgressDrawable color programatically.

ProgressBar splashProgressBar = (ProgressBar)findViewById(R.id.splashProgressBar);

Drawable bgDrawable = splashProgressBar.getProgressDrawable();
bgDrawable.setColorFilter(Color.BLUE, android.graphics.PorterDuff.Mode.MULTIPLY);
splashProgressBar.setProgressDrawable(bgDrawable);

Hope this will help you.


This post is what you're looking for: How to change progress bar's progress color in Android

If you want the user to choose their own colors, just make multiple-drawable XML files for each color, and select them based on the user's choice.


Layout = activity_main.xml:

<ProgressBar
    android:id="@+id/circle_progress_bar_middle"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:max="100"
    android:rotation="-90"
    android:indeterminate="false"
    android:progressDrawable="@drawable/my_drawable_settings2" />

In Java Activity/Fragment:

ProgressBar myProgressBar = (ProgressBar) view.findViewById(R.id.circle_progress_bar_middle);
myProgressBar.setProgressDrawable(getResources().getDrawable(R.my_drawable_settings1));

The my_drawable_settings1.xml file inside your drawable/mipmap folder:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/progress">
        <shape
            android:innerRadius="55dp"
            android:shape="ring"
            android:thickness="9dp"
            android:useLevel="true">

            <gradient
                android:startColor="#3594d1"
                android:endColor="@color/white"
                android:type="sweep" />
        </shape>
    </item>
</layer-list>

Where my_drawable_settings1 and my_drawable_settings2.xml has different colors.

ReferenceURL : https://stackoverflow.com/questions/10951978/change-progressbar-color-through-code-only-in-android

반응형