冲突原因:ListView本身是自带滚动条的,因为它继承ScrollView,所以,在ScrollView中所嵌套的布局内有ListView时,若ListView的高度为自适应或是充满,JVM就无法计算ListView的高度,导致ListView只能显示一行或一行多一点。
解决方法:新建一个控件类,继承ListView,重写OnMesure方法。(OnMesure方法的作用是告诉父控件,让父控件分配空间)
具体代码及步骤如下:
致敬:http://bbs.itheima.com/thread-128002-1-1.html
1.新建一个类,继承LlistView
package com.example.scrolltest;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MListView extends ListView {
//写三个构造器
public MListView(Context context) {
super(context);
}
public MListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
//重写onMeasure方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
2.在布局中引用该控件
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="@drawable/ic_launcher"/>
<com.example.scrolltest.MListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
3.在代码中把新控件视为ListView使用(代码略)
注意:界面显示时会直接跳到最后item处,解决方法有两个
1,在为新ListView添加数据源时,所用List集合调用add()方法时,使用add(0,map)。
用这个方法新添加的数据会靠上。不过,这样只能移动到item的最顶端,界面上方的控件还需要下拉才能看见。
2,ScrollView调用smoothScrollTo(0, 0)方法,即将界面移动至最上方。