【问题标题】:Dynamic horizontal progressbar width not showing full width in android [duplicate]动态水平进度条宽度未在android中显示全宽[重复]
【发布时间】:2017-09-10 11:09:20
【问题描述】:

我正在创建动态进度条宽度,但它现在可以正常显示。当我在 xml 中设置宽度(272 dp)时,它显示正确,但我以编程方式设置相同的宽度,它没有显示正确的宽度。

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" />

代码:

    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) progressBarList.get(2).getLayoutParams();
params.width = 272;
        progressBarList.get(2).setLayoutParams(params);
        progressBarList.get(2).invalidate();

【问题讨论】:

  • 因为 params.width=272 以像素为单位。并在 xml 中设置 dp 值
  • @DivyeshPatel 我该怎么做才能得到准确的结果?

标签: android android-progressbar


【解决方案1】:

使用:

progressWidth= convertDpToPixels(272, this);

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

另一个公式:

public static float convertDpToPixel(float dp){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return Math.round(px);
}

【讨论】:

  • COMPLEX_UNIT_DP 不可用,我应该使用 DIP
  • 用 DIP 改变它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2013-04-03
  • 2014-01-25
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
相关资源
最近更新 更多