Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does getMeasuredHeight() return values in pixels or dp

i am trying to get the height of the items in a listview programmatically. so i referred to som epost in our website and i came out with following code

    private float calcListViewItemsHeight(ListView listView) {
    Log.d(TAG, getApplicationContext().getResources().getResourceEntryName(listView.getId()) + ".getCount() :" + listView.getCount());

    int height = 0;
    for (int i = 0; i < listView.getCount(); i++) {
        View childView = listView.getAdapter().getView(i, null, listView);
        childView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        height+= childView.getMeasuredHeight();
    }

    //dividers height
    height += listView.getDividerHeight() * listView.getCount();

    Log.d(TAG, getApplicationContext().getResources().getResourceEntryName(listView.getId()) + "totalHeight in px: " + height);

    float dp = this.px2dp(height);
    Log.d(TAG, getApplicationContext().getResources().getResourceEntryName(listView.getId()) + "totalHeight in dp: " + dp);

    return dp;
    //return height;
}

the value returned from the above code, supposedly to be in pixels, which mean i have to convert it into dp so my code can work fine on different screen sizes. to convert from pixels to dp i used the followin gcode:

private float px2dp(int pxVal) {
    float density = this.getResources().getDisplayMetrics().density;

    return (pxVal/ density);
}

now, as my list contains 4 items, i get the following logCat output which represents the number of the items contains in the listview and the height of the listview in both pixels and dp, this reults comes from 'calcListViewItemsHeight' posted above

12-10 10:27:40.817 D/VersDetailActivity2: versicherungsListeActivity2mod_lisVie_versDetails.getCount() :4
12-10 10:27:40.822 D/VersDetailActivity2: versicherungsListeActivity2mod_lisVie_versDetailstotalHeight in px: 533
12-10 10:27:40.822 D/VersDetailActivity2: versicherungsListeActivity2mod_lisVie_versDetailstotalHeight in dp: 266.5

what i could not understand is, when the method 'calcListViewItemsHeight' returns 'height' i got the listview of a height as shown in img_1, but if 'calcListViewItemsHeight' returned 'dp' i got a listview of height as shown in img_2

does 'getMeasuredHeight()' returns value in dp or pixels?

img_1:

enter image description here

img_2:

enter image description here

like image 235
user2121 Avatar asked Dec 10 '16 09:12

user2121


1 Answers

Documentation said that the return value is "The raw measured height of this view." And from here "raw" means pixels. And may be this link also helps You.

like image 155
Andrii Omelchenko Avatar answered Sep 19 '22 08:09

Andrii Omelchenko