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

RecyclerView生成Bitmap时因列表项包含CircularProgressIndicator抛出AndroidRuntimeException

RecyclerView生成Bitmap时因列表项包含CircularProgressIndicator抛出AndroidRuntimeException

我之前也碰到过一模一样的情况——用getScreenshotFromRecyclerView在AsyncTask的后台线程生成Bitmap转PDF本来好好的,结果一加CircularProgressIndicator就直接抛出异常了。其实问题根源很清晰:CircularProgressIndicator是带动画的UI控件,Android要求动画相关的绘制操作必须在UI线程执行,而你在后台线程(doInBackground方法)里触发它的绘制,就会触发系统的线程安全检查,进而抛出AndroidRuntimeException。

给你几个实用的解决办法,按操作复杂度从低到高排序:

方案一:截图临时隐藏/禁用进度指示器

这是最省心的办法,截图前把所有可见列表项里的CircularProgressIndicator暂时隐藏,截图完成后再恢复原有状态:

// 截图前遍历RecyclerView可见子项,隐藏进度指示器
for (int i = 0; i < recyclerView.getChildCount(); i++) {
    View listItem = recyclerView.getChildAt(i);
    CircularProgressIndicator indicator = listItem.findViewById(R.id.your_progress_indicator_id);
    if (indicator != null) {
        // 先保存原来的显示状态,方便后续恢复
        indicator.setTag(indicator.getVisibility());
        indicator.setVisibility(View.INVISIBLE);
    }
}

// 执行截图操作
Bitmap recyclerBitmap = getScreenshotFromRecyclerView(recyclerView);

// 截图完成后恢复进度指示器的原始状态
for (int i = 0; i < recyclerView.getChildCount(); i++) {
    View listItem = recyclerView.getChildAt(i);
    CircularProgressIndicator indicator = listItem.findViewById(R.id.your_progress_indicator_id);
    if (indicator != null) {
        int originalVisibility = (int) indicator.getTag();
        indicator.setVisibility(originalVisibility);
    }
}

方案二:把截图操作移到UI线程执行

既然动画控件只能在UI线程正常绘制,那我们就把截图逻辑放到UI线程完成,之后再回到后台线程处理PDF生成:

@Override
protected Void doInBackground(Void... voids) {
    // 用CountDownLatch同步UI线程的截图操作,避免后台线程提前执行后续逻辑
    final CountDownLatch latch = new CountDownLatch(1);
    final Bitmap[] resultBitmap = new Bitmap[1];

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                resultBitmap[0] = getScreenshotFromRecyclerView(recyclerView);
            } finally {
                latch.countDown();
            }
        }
    });

    try {
        // 等待UI线程完成截图
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // 现在可以在后台线程用生成好的Bitmap转PDF了
    if (resultBitmap[0] != null) {
        generatePdfFromBitmap(resultBitmap[0]);
    }
    return null;
}

额外提醒

顺便提一句,AsyncTask在Android 11及以上版本已经被官方废弃了,如果是新项目,建议改用Kotlin协程或者WorkManager来处理后台任务,线程管理会更灵活规范哦。

备注:内容来源于stack exchange,提问作者len

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 17:33:20