我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
我已经为分辨率为480x800的Pantech设备创建了以像素为单位的高度和宽度的应用程序。
我需要转换G1设备的高度和宽度。 我认为将其转换为dp将解决问题,并为两个设备提供相同的解决方案。
有没有什么简单的方法将像素转换为dp? 有什么建议吗?
当前回答
根据Android开发指南:
px = dp * (dpi / 160)
但通常当你收到以像素表示的设计时,你会希望以另一种方式执行这个操作。所以:
dp = px / (dpi / 160)
如果你在一个240dpi的设备上,这个比例是1.5(如前所述),所以这意味着一个60px的图标在应用程序中等于40dp。
其他回答
((MyviewHolder) holder).videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
((MyviewHolder) holder).spinnerView.setVisibility(View.GONE);
mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/*
* add media controller
*/
MediaController controller = new MediaController(mContext);
float density = mContext.getResources().getDisplayMetrics().density;
float px = 55 * density;
// float dp = somePxValue / density;
controller.setPadding(0, 0, 0, (int) (px));
((MyviewHolder) holder).videoView.setMediaController(controller);
}
});
}
});
如果您想要整数值,则使用Math.round()将浮点数四舍五入为最接近的整数。
public static int pxFromDp(final float dp) {
return Math.round(dp * Resources.getSystem().getDisplayMetrics().density);
}
最好放在Util.java类中
public static float dpFromPx(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
public static float pxFromDp(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
上面有很多很棒的解决方案。然而,我发现最好的解决方案是谷歌的设计:
https://design.google.com/devices/
将像素转换为dp使用TypedValue。
正如文档中提到的:动态类型数据值的容器。
并使用applyDimension方法:
public static float applyDimension (int unit, float value, DisplayMetrics metrics)
将一个保存维度的已解包的复杂数据值转换为其最终浮点值,如下所示:
Resources resource = getResources();
float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 69, resource.getDisplayMetrics());
希望能有所帮助。