Android和在DP单位设置宽度和高度编程 [英] Android and setting width and height programmatically in dp units

查看:509
本文介绍了Android和在DP单位设置宽度和高度编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的:

button.setLayoutParams(新GridView.LayoutParams(65,65));

根据文档的单位的宽度和高度(在上面的两个65)是像素。你如何强制这是设备无关的像素,或者DP?

According to the docs the units for the width and height (both 65 in the above) are "pixels". How do you force this to be device independent pixels, or "dp"?

推荐答案

您就必须将它从DPS转换为使用的显示比例系数像素。

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

这篇关于Android和在DP单位设置宽度和高度编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆