android 解决ScrollView嵌套ListView的问题,不能全屏,全屏不能显示下面控件

在开发中遇到ScrollView嵌套ListView的问题,最开始发出不能全屏,效果是这样的;

但我想要的效果是这样的:


下面看一下布局文件:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <ListView
        android:id="@+id/lvDemo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"></LinearLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="15dp"
        android:text="添加一项" />
    </LinearLayout>
</ScrollView>

网上说在ScrollView 加入

android:fillViewport="true"
但同样存在问题,当listview 长度大于屏幕高度时,展示的效果是只能显示listview ,不能正常显示下面的按钮控件;

效果如下:


下面看一下最终的解决方案:

如果对自定义控件熟识的人,肯定想到解决方案了,重写listview ;

/**
 * Created by http://blog.csdn.net/q610098308 on 2015/12/17.
 */
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 = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                View.MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
下面普及一下:

OnMeasure一些知识;

我们把布局文件的宽和高写成wrap_content,会发现效果并不是我们的,系统帮我们测量的高度和宽度都是MATCH_PARNET,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,当我们设置为WRAP_CONTENT,或者MATCH_PARENT系统帮我们测量的结果就是MATCH_PARENT的长度。

所以,当设置了WRAP_CONTENT时,我们需要自己进行测量,即重写onMesure方法”:

重写之前先了解MeasureSpec的specMode,一共三种类型:

EXACTLY:一般是设置了明确的值或者是MATCH_PARENT

AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT

UNSPECIFIED:表示子布局想要多大就多大,很少使用


这里我们直接告诉系统我们设置是AT_MOST;




posted @ 2015-12-18 09:38  恋恋西风  阅读(428)  评论(0编辑  收藏  举报