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

Android GridLayout嵌套LinearLayout实现图片增删后重排报错求解

问题根因排查
    1. 数组越界崩溃:sortImages() 方法循环范围是i < table.getChildCount(),内部执行table.getChildAt(i+1)时,当i为最后一个下标会超出子View总数,直接触发崩溃
    1. 空指针异常:直接强转imgHolder.getChildAt(0)为ImageView,无图片的LinearLayout没有子View,强转直接触发空指针
    1. 多选逻辑错误:addMultPhoto()中未判断单元格是否为空就直接插入图片,且遍历ClipData时下标未自减,会重复插入同一张图片
    1. 数据存储逻辑错误:完全依赖视图组件存储图片状态,没有独立的数据层维护选中的图片Uri,重排逻辑复杂度大幅提升
    1. Intent配置错误:Intent.CATEGORY_OPENABLE需要用addCategory()添加,原代码中用putExtra()传递完全不生效
修复方案

第一步:新增全局数据列表维护选中图片

在Activity成员变量中添加Uri列表,不再依赖视图存储状态:

private ArrayList<Uri> selectedUris = new ArrayList<>();
// 最多支持6张图片,对应2行3列
private static final int MAX_PIC_COUNT = 6;

第二步:新增全局刷新Grid方法,自动重排无间隙

private void refreshGrid() {
    // 先清空所有单元格内容
    for (int i = 0; i < table.getChildCount(); i++) {
        LinearLayout cell = (LinearLayout) table.getChildAt(i);
        cell.removeAllViews();
    }
    // 按顺序给前N个单元格填图片
    for (int i = 0; i < selectedUris.size(); i++) {
        if (i >= MAX_PIC_COUNT) break;
        LinearLayout cell = (LinearLayout) table.getChildAt(i);
        cell.addView(imageViewCreater(selectedUris.get(i)));
    }
}

第三步:修复图片选择逻辑

修改onActivityResult,优先更新数据列表再刷新视图:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode != RESULT_CANCELED && requestCode == SELECT_IMAGE_GALLERY) {
        ClipData clip = data.getClipData();
        // 单选
        if(clip == null && data.getData() != null){
            if (selectedUris.size() < MAX_PIC_COUNT) {
                selectedUris.add(data.getData());
            }
        // 多选
        }else if(clip != null){
            int addCount = Math.min(clip.getItemCount(), MAX_PIC_COUNT - selectedUris.size());
            for (int i = 0; i < addCount; i++) {
                selectedUris.add(clip.getItemAt(i).getUri());
            }
        }
        refreshGrid();
    }
}

删除原有的addSinglePhoto、addMultPhoto、sortImages方法,不需要再手动实现重排逻辑。

第四步:修复长按删除逻辑

img.setOnLongClickListener(new View.OnLongClickListener(){
    @Override
    public boolean onLongClick(View view){
        // 找到当前点击的单元格下标
        int position = table.indexOfChild(view);
        // 下标在已选图片范围内才执行删除
        if (position < selectedUris.size()) {
            selectedUris.remove(position);
            refreshGrid();
        }
        return true;
    }
});

第五步:修复跳转相册的Intent配置

Intent toPhonePhotos = new Intent(Intent.ACTION_GET_CONTENT);
toPhonePhotos.setType("image/*");
toPhonePhotos.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
// 修复CATEGORY_OPENABLE的添加方式
toPhonePhotos.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(toPhonePhotos, "select Picture"), SELECT_IMAGE_GALLERY);

可选优化:修改布局属性

把GridLayout的android:columnOrderPreserved改为false,避免后续调整单元格位置时被限制:

android:columnOrderPreserved="false"

内容的提问来源于stack exchange,提问作者Jzon Livingston jr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 09:15:08