需要计算list中显示条目的个数,然后在在代码中设置listview的高度。
这里看看我怎么实现的
我们的布局代码:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/search_title_layout"
android:orientation="vertical">
<com.xis.read.view.ListViewForScrollView
android:id="@+id/lv_history"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_clear_history"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector_common_gray_background"
android:gravity="center"
android:padding="10dp"
android:text="@string/claer_history"
android:textColor="@color/readpage_rose" />
</LinearLayout>
上面的重要的只有一条ListView的高度用wrap_content
接下来我们只要自定义ListView就好了。这个自定义ListView也可以用于ScrollView中嵌套使用
package cn.xs.reader.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* Created by Saud on 16/2/15.
*/
public class ListViewForScrollView extends ListView {
public ListViewForScrollView(Context context) {
super(context);
}
public ListViewForScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
/**
* 重写该方法,达到使ListView适应ScrollView的效果
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}