关于ScrollView中嵌套Listview和GridView的解决方案

  • 这里的方法是通过在listview或者GridView内部定义一个方法,然后在setAdapter()后调用的
    • 地址是:http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
    • 这里是代码
public class ExpandableHeightGridView extends GridView {

    boolean expanded = false;

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

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

    public ExpandableHeightGridView(Context context, AttributeSet attrs,
            int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public boolean isExpanded()
    {
        return expanded;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // HACK! TAKE THAT ANDROID!
        if (isExpanded())
        {
            // 计算整个高度,提供一个非常大的高度提示.
            // View.MEASURED_SIZE_MASK 代表可能的最大高度.
            //后面的AT_MOST代表的是包裹内容(指的是SpecMode)
            int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
                    MeasureSpec.AT_MOST);
                    //将这个传入给super的高度
            super.onMeasure(widthMeasureSpec, expandSpec);
                //得到布局lp,设置高度!
            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        }
        else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setExpanded(boolean expanded)
    {
        this.expanded = expanded;
    }
}
  • 如何调用
gridView.setAdapter(new MyAdpter());
gridView.setExpanded(true);
  • 布局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.karl.draggridview.MainActivity">

    <GridView  android:id="@+id/drag_grid_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:horizontalSpacing="10dp" android:numColumns="4" android:verticalSpacing="10dp" android:scrollbars="vertical" android:stretchMode="columnWidth" android:gravity="center">

    GridView>
ScrollView>

你可能感兴趣的:(自定义View)