Getheight() Px Or Dpi?
Help.I found the height of ListView and I do not know px or dpi? I need dpi final ListView actualListView = mPullRefreshListView.getRefreshableView(); actualListView.getViewTreeOb
Solution 1:
getheight return height in pixels, Below is what docs says..
publicfinalintgetHeight()Since: API Level 1
Return the height of your view. Returns
The height of your view, in pixels.
You need to convert px into dp , use below ways to convert it to dp.
Convert pixel to dp:
publicintpxToDp(int px) {
DisplayMetricsdisplayMetrics= getContext().getResources().getDisplayMetrics();
intdp= Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
}
or if you want it in px use below.
Convert dp to pixel:
publicintdpToPx(int dp) {
DisplayMetricsdisplayMetrics= getContext().getResources().getDisplayMetrics();
intpx= Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
Solution 2:
It returns pixels. http://developer.android.com/reference/android/view/View.html#getHeight() To convert pixels to dpi use this formula px = dp * (dpi / 160)
Solution 3:
Using this code you can get runtime Display's Width & Height
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
intheight= displaymetrics.heightPixels;
intwwidth= displaymetrics.widthPixels;
Solution 4:
The functions for converting dp to px and px to dp should look like below (in kotlin):
funconvertDpToPx(dp: Int): Int {
val metrics = Resources.getSystem().displayMetrics
return dp * (metrics.densityDpi / 160f).roundToInt()
}
funconvertPxToDp(px: Int): Int {
val metrics = Resources.getSystem().displayMetrics
return (px / (metrics.densityDpi / 160f)).roundToInt()
}
Post a Comment for "Getheight() Px Or Dpi?"