1

I am creating dynamic progressbar width but it's now showing properly. When i set width (272 dp ) in xml it's showing properly but i am setting same width programmetically it's not showing correct width.

XML:

<ProgressBar
                            android:id="@+id/progress_bar_sleep"
                            style="@style/SleepProgress"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="@dimen/text_size_16dp"
                            android:layout_marginTop="@dimen/default_gap" />

Code :

    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) progressBarList.get(2).getLayoutParams();
params.width = 272;
        progressBarList.get(2).setLayoutParams(params);
        progressBarList.get(2).invalidate();
Shanmugapriyan M
  • 301
  • 5
  • 17

1 Answers1

2

use :

progressWidth= convertDpToPixels(272, this);

 public int convertDpToPixels(float Dp, Context context) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DP, Dp, context.getResources().getDisplayMetrics());
    }

Another formula:

public static float convertDpToPixel(float dp){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return Math.round(px);
}
Divyesh Patel
  • 2,576
  • 2
  • 15
  • 30