如何在dips中以编程方式设置窗口小部件的宽度

时间:2013-07-06 19:36:17

标签: android android-layout

我正在动态地向窗格添加窗口小部件。 我需要通过以下代码将小部件宽度设置为100:
宽度= 100; 如何将上面给定的值转换为android

中的dps

1 个答案:

答案 0 :(得分: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;
}

信用:Converting pixels to dp