正确的方式来获得DisplayMetrics:getResources()或getWindowManager()正确、方式、DisplayMetrics、getResources

由网友(一個人守著過去)分享简介:什么是正确的方式来获得DisplayMetrics,即让屏幕/显示信息,如密度或 xdpi ?我问,因为我已经看到了会对此有两种方式:第一:DisplayMetrics指标=新DisplayMetrics();。getWindowManager()getDefaultDisplay()getMetrics(度量)。然后...

什么是正确的方式来获得DisplayMetrics,即让屏幕/显示信息,如密度 xdpi

我问,因为我已经看到了会对此有两种方式:

第一:

  DisplayMetrics指标=新DisplayMetrics();
    。getWindowManager()getDefaultDisplay()getMetrics(度量)。
 

然后获取信息通过 metrics.density metrics.xdpi

第二:

  getResources()。getDisplayMetrics()。密度
 

在这个方法,我相信你也可以只初始化一个变量来保存DisplayMetric再抓信息像第一种方法:

  DisplayMetrics metricsMethodTwo = getResources()。getDisplayMetrics()
 
XP1985 2004系统安装问题在网上搜了很多教程,但是没有一个是一样的吖,搞得我都糊涂了,求大神准确教我设置.

然后你可以像正常的信息: metricsMethodTwo.density metricsMethodTwo.xdpi

我同在一个文档不同的地方看到。那么,如果有任何差异,当一种方法的青睐(或更合适),在其他的,为什么?谢谢

解决方案

 公共DisplayMetrics getDisplayMetrics()
 

  

返回当前显示的指标这实际上是对这一资源对象。返回的对象应被视为只读的。

 公共无效getMetrics(DisplayMetrics outMetrics)
 

  

从这个显示数据初始化DisplayMetrics对象的

不同的是,由返回资源的指标方法是度量该特定资源对象。您可以随时创建一个新的资源实例的构造函数

 资源(AssetManager资产,DisplayMetrics指标,配置配置)
 

在这你可以设置你想要的任何指标,不一定可以从显示的方法实例返回得到的指标 getDefaultDisplay()

这就是区别。如果你只使用默认的资源和默认显示的值,它可能不会有所作为,但。

What's the proper way to get DisplayMetrics, i.e. get screen/display info such as density or xdpi?

I ask because I've seen two ways of going about this:

FIRST:

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

then getting the info by metrics.density or metrics.xdpi, etc

SECOND:

    getResources().getDisplayMetrics().density

in this method I believe you can also just initialize a variable to hold the DisplayMetric and then grab info like in the FIRST method:

    DisplayMetrics metricsMethodTwo = getResources().getDisplayMetrics()

and then you can get info like normal: metricsMethodTwo.density or metricsMethodTwo.xdpi

I've seen both in various places in the Docs. So what are the differences if any, and when is one method favored (or more appropriate) over the other and why? Thanks

解决方案

public DisplayMetrics getDisplayMetrics ()

Return the current display metrics that are in effect for this resource object. The returned object should be treated as read-only.

public void getMetrics (DisplayMetrics outMetrics)

Initialize a DisplayMetrics object from this display's data.

The difference is that the metrics returned by the Resources method is the metrics for that particular Resources object. You can always create a new Resources instance with the constructor

Resources(AssetManager assets, DisplayMetrics metrics, Configuration config)

in which you can set any metrics you want, not necessarily the metrics you can get from the Display instance returned by the method getDefaultDisplay().

That's the difference. It may not make a difference though in the values if you're using just the default resources and the default display.

阅读全文

相关推荐

最新文章