当 ListView 被嵌套在 ScrollView 等滑动控件中,只能展示一行,这时候就需要自定义了
代码如下:
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zhh.android.MainActivity"
android:orientation="vertical"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.zhh.android.NoScrollListView
android:id="@+id/noScrollListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.zhh.android.NoScrollListView>
</ScrollView>
</LinearLayout>
自定义控件 NoScrollListView
/**
*
* 自定义 ListView
* 当在滚动布局中,listView 显示一行,通过测量listView条目加起来的总高度
* 使 listView 全部展开
*/
public class NoScrollListView extends ListView {
public NoScrollListView(Context context) {
super(context);
}
public NoScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// 重写onMeasure方法,以便自行设定视图的高度
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 将高度设为最大值,即所有项加起来的总高度
// AT_MOST 测量模式,对应的就是 MATCH_PARENT 与父布局的尺寸一样,就是listView的总高度
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
源码下载:
TestCustom ---- app3
https://download.youkuaiyun.com/download/zhaihaohao1/11224806