[全屏查看所有代码]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
void
setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if
(listAdapter ==
null
) {
return
;
}
int
totalHeight =
0
;
for
(
int
i =
0
; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i,
null
, listView);
listItem.measure(
0
,
0
);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -
1
));
((MarginLayoutParams)params).setMargins(
10
,
10
,
10
,
10
);
listView.setLayoutParams(params);
}
|
2. [代码]XML布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<ScrollView
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
android:fadingEdge =
"none"
android:background=
"#FFF4F4F4"
xmlns:android=
"http://schemas.android.com/apk/res/android"
>
<LinearLayout
android:gravity=
"center_horizontal"
android:orientation=
"vertical"
android:background=
"#fff4f4f4"
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
>
<ListView
android:id=
"@+id/moreItemsListView"
android:layout_width=
"fill_parent"
android:layout_height=
"fill_parent"
android:cacheColorHint=
"#FFF4F4F4"
android:dividerHeight=
"0.0dip"
android:fadingEdge=
"none"
/>
</LinearLayout>
</ScrollView>
|
4. [代码]重写ListView解决item高度不一致的问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
MyListView
extends
ListView {
public
MyListView(Context context) {
super
(context);
}
public
MyListView(Context context, AttributeSet attrs) {
super
(context, attrs);
}
public
MyListView(Context context, AttributeSet attrs,
int
defStyle) {
super
(context, attrs, defStyle);
}
@Override
protected
void
onMeasure(
int
widthMeasureSpec,
int
heightMeasureSpec) {
int
expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>
2
,
MeasureSpec.AT_MOST);
super
.onMeasure(widthMeasureSpec, expandSpec);
}
}
|