范例:
1.MainActivity代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
public
class
MainActivity
extends
Activity
{
// 只要在设置ListView的Adapter后调用此静态方法Utility.setListViewHeightBasedOnChildren(listview);
// 即可让ListView正确的显示在其父ListView的ListItem中。
// 但是要注意的是,子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)
// 没有重写onMeasure(),所以会在onMeasure()时抛出异常。
private
ArrayList<String> dataList;
private
ListView listview;
private
ImageView img;
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList =
new
ArrayList<String>();
for
(
int
i =
0
; i <
5
; i++)
{
String str =
"第"
+ i +
"行"
;
dataList.add(str);
}
img = (ImageView) findViewById(R.id.imageView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(
new
BaseAdapter()
{
@Override
public
View getView(
int
position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.item,
null
);
TextView tv = (TextView) layout.findViewById(R.id.tv_item);
String str = dataList.get(position);
tv.setText(str);
return
layout;
}
@Override
public
long
getItemId(
int
position)
{
return
0
;
}
@Override
public
Object getItem(
int
position)
{
return
null
;
}
@Override
public
int
getCount()
{
return
dataList.size();
}
});
Utility.setListViewHeightBasedOnChildren(listview);
}
}
|
2.Utility代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public
class
Utility
{
public
static
void
setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if
(listAdapter ==
null
)
{
// pre-condition
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
));
listView.setLayoutParams(params);
}
}
|
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1290605,如需转载请自行联系原作者