In order achieve wrap_content
height in ListView
, we need to use CustomListView
that extends
our native ListView
.
MyListView.java
public class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
in your layout
use custom view like this,
layout.xml
<com.yourpackagename.MyListView
...
android:layout_width="match_parent"
android:layout_height="wrap_content"
... />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…