I am calculating the height of some items in a ListView and then I assign the calculated height to the ListView programmatically to ensure that the ListView will expand to accommodate its contents. I calculated the height of the items in the ListView as shown below in the code.
As shown in the code, the following line returns a value equal to 533:
height += listView.getDividerHeight() * listView.getCount();//
The problem I have is, when the height of the ListView is set to the value returned "533" as shown in the code, the ListView has exactly the same heights as its contents. But when I set the same value "533" to the ListView throughout "android:layout_height" in the XML file, then the ListView expands too much beyond its contents "higher than its contents"
So my questions are:
Please explain why that is happening?
As for the posted code, when I change the 'TypedValue.COMPLEX_UNIT_DIP' to any other unit like 'TypedValue.COMPLEX_UNIT_PX' there no change at all. Why there is no effect when changing the unit of the LayoutParameter?
code:
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();// returns 533
param = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, this.getResources().getDisplayMetrics()));
param.addRule(RelativeLayout.BELOW, ruleSubject);
container.setLayoutParams(param);
listView.requestLayout();