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

Android Lint警告:TypedArray未使用try-with-resources,如何解决?

解决TypedArray的Lint警告:未使用try-with-resources语句

你遇到的Lint警告是因为TypedArray属于需要手动回收的资源,虽然当前代码最后调用了attributes.recycle(),但如果中间代码抛出异常,recycle()可能无法执行,存在资源泄漏风险。Android Lint推荐使用try-with-resources语法,它能自动在代码块执行完毕(无论正常结束还是抛出异常)时回收资源,避免这类问题。

修改后的完整代码

public RVIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // 使用try-with-resources自动回收TypedArray
    try (TypedArray attributes = context.obtainStyledAttributes(
            attrs, R.styleable.RVIndicator, defStyleAttr, R.style.RVIndicator)) {
        dotColor = attributes.getColor(R.styleable.RVIndicator_dotColor, 0);
        selectedDotColor = attributes.getColor(R.styleable.RVIndicator_dotSelectedColor, dotColor);
        dotNormalSize = attributes.getDimensionPixelSize(R.styleable.RVIndicator_dotSize, 0);

        spaceBetweenDotCenters = attributes.getDimensionPixelSize(R.styleable.RVIndicator_dotSpacing, 0) + dotNormalSize;
        looped = attributes.getBoolean(R.styleable.RVIndicator_looped, false);
        int visibleDotCount = attributes.getInt(R.styleable.RVIndicator_visibleDotCount, 0);
        setVisibleDotCount(visibleDotCount);
        visibleDotThreshold = 0;
    } // 无需手动调用recycle(),try-with-resources会自动处理

    paint = new Paint();
    paint.setAntiAlias(true);

    if (isInEditMode()) {
        setDotCount(visibleDotCount);
        onPageScrolled(visibleDotCount / 2, 0);
    }
}

修改说明

  • 将TypedArray的初始化语句放入try()括号内:这是try-with-resources的标准语法,适用于实现AutoCloseable接口的类(TypedArray在API 21及以上版本实现了该接口,其close()方法内部会调用recycle()完成资源回收)。
  • 移除手动调用的attributes.recycle():try-with-resources会在代码块结束后自动执行资源回收,无论代码块是正常完成还是抛出异常。
  • 所有操作TypedArray的逻辑都包裹在try代码块内,确保资源仅在有效生命周期内被访问。

内容的提问来源于stack exchange,提问作者Chaitanya Karmarkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:35:20