防止GridView缩放

时间:2015-04-08 23:57:13

标签: android gridview scroll

如何通过自动调整gridView的高度来保持gridView不需要滚动?我想要所有项目,无论我添加到gridView的多少项目都保留在屏幕上而不滚动。这可能吗?

到目前为止,这是我的用户界面。

<?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:background="@drawable/bg"
    android:orientation="vertical">

        <GridView
            android:id="@+id/gv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tv_header"
            android:fadingEdge="none"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:gravity="center"
            android:listSelector="#00000000"
            android:numColumns="auto_fit"
            android:stretchMode="columnWidth" />

</LinearLayout>

我确实尝试将weightSum添加到根目录并将权重添加到gridView但仍需要滚动。

更新:我也尝试使用自定义gridview。这不起作用,但无论如何这是我的尝试。

public class CustomGridView extends GridView {

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

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

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

    @Override 
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST));
        getLayoutParams().height = getMeasuredHeight();
    } 
} 

提前致谢!

1 个答案:

答案 0 :(得分:1)

我找到了答案。您可以使用

设置适配器中每个项目的高度
view.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, resizeValue));

resizeValue是您要调整行的大小。要获取resizeValue,您可以根据与设备屏幕大小相关的计算传递给适配器mResizeValue。像

这样的东西
resizevalue = this.getResources().getDisplayMetrics().heightPixels / (NUM_COLS);

我根据屏幕大小找出了计算每行高度的其他方法然后做了类似的事情,但是,这需要在设置适配器然后更新适配器更改后进行这些计算。效率似乎不高,但我也会分享这种方法。

private void resizeGridView(GridView gridView, int items, int columns) {
    ViewGroup.LayoutParams params = gridView.getLayoutParams();
    int oneRowHeight = gridView.getHeight();
    int rows = (int) (items / columns);
    params.height = oneRowHeight * rows;
    gridView.setLayoutParams(params);
} 

然后在设置适配器后使用

gridView.getViewTreeObserver().addOnGlobalLayoutListener(new 

    ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (!gridViewResized) {
                        gridViewResized = true;
                        resizeGridView(gridView, numItems, numColumns);
                    }
                }
            });
相关问题