首页 > 代码库 > Listview或者GridView嵌套在ScrollView中只显示一行item解决方法。

Listview或者GridView嵌套在ScrollView中只显示一行item解决方法。

 页面里有ListView(GridView)和一些固定布局让他们一起在整个屏幕上滚动方法:

(1)自定义ListView(GridView),重写onMeasure()方法,我以GridView为例(ListView只需要extends ListView)具体代码如下:
package top.ant.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class AntGridView extends GridView {

    public AntGridView(Context context) {
        super(context);
    }

    public AntGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AntGridView(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)在布局文件中将整个布局放在ScollerView中,要使用的GridView或者ListView使用自定义的HeaderGridView,具体xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="180dp"
                android:background="#00aa00">
                
            </LinearLayout>

            <!-- 一定要是自定义View的包名和类名 -->
            <top.ant.view.AntGridView
                android:id="@+id/ant_live_index_gridview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:numColumns="2">

            
            </top.ant.view.AntGridView>
        </LinearLayout>
    </ScrollView>


</LinearLayout>

Listview或者GridView嵌套在ScrollView中只显示一行item解决方法。