You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android GridView自动调整行高适配屏幕无多余空白如何实现

错误原因

你之前直接用屏幕总高度计算行高,没有扣除AppBar、状态栏等其他视图占用的空间,也没有计算GridView设置的垂直间距,导致算出的行高超出GridView实际可用范围,才会出现多余空白。

解决方案

1. 先修改网格项布局

将item布局里内层inputDataGridValues的高度属性改为match_parent,确保内容可以填充满整个item高度:

<RelativeLayout
    android:id="@+id/inputDataGridValues"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="#fff"
    >
    <!-- 原有内部控件不变 -->
</RelativeLayout>

2. 正确计算行高

不要在getView中重复计算高度,在Fragment/Activity的布局渲染完成后,直接拿GridView的实际可用高度计算,避免误差:

// 在你的Fragment的onViewCreated方法中添加以下代码
inputDataGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // 移除监听避免重复触发
        inputDataGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        // 拿到GridView的实际可用高度(已经自动扣除了AppBar、状态栏等占用的空间)
        int gridHeight = inputDataGrid.getHeight();
        // 你的网格行数,按你的需求填3
        int rowCount = 3;
        // 计算总垂直间距:行数-1 * 你设置的1dp垂直间距,转成px
        float spacingPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
        int totalSpacing = (int) ((rowCount - 1) * spacingPx);
        // 算出正确的单行高度
        int itemHeight = (gridHeight - totalSpacing) / rowCount;
        // 将高度传给Adapter
        yourGridAdapter.setItemHeight(itemHeight);
        yourGridAdapter.notifyDataSetChanged();
    }
});

3. 调整Adapter中高度设置逻辑

在Adapter中新增成员变量存储计算好的行高,getView中直接设置即可:

public class YourGridAdapter extends BaseAdapter {
    private int mItemHeight = 0;

    // 提供设置行高的方法
    public void setItemHeight(int height) {
        mItemHeight = height;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        InputDataType inputDataType = getItem(position);
        if (convertView == null) { 
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false); 
        }
        // 直接设置item高度
        if (mItemHeight > 0) {
            AbsListView.LayoutParams params = (AbsListView.LayoutParams) convertView.getLayoutParams();
            params.height = mItemHeight;
            convertView.setLayoutParams(params);
        }
        ImageView icon = (ImageView) convertView.findViewById(R.id.itemImage);
        TextView text = (TextView) convertView.findViewById(R.id.itemTitle);
        // 原有设置图标和标题的逻辑不变
        return convertView;
    }
}

通过以上步骤即可实现GridView行高正好填充满可用空间,不会出现多余空白。

内容的提问来源于stack exchange,提问作者Savan Luffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:48:03