-1

我正在动态地将小部件添加到布局中。我需要通过如下代码将小部件宽度设置为 100:
Width = 100; 如何在android中将上述给定值转换为dps

4

1 回答 1

1
/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}

信用:将像素转换为 dp

于 2013-07-06T19:49:18.207 回答