Proper way to get DisplayMetrics: getResources() or getWindowManager()
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 开发者_JAVA技巧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.
精彩评论