Android lint警告使用了没有try-with-resources语句的'TypedArray'。如何解决?

3
我有以下代码:
 public RVIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    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;
    attributes.recycle();

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

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

对于以下语句,lint 给出了警告:“使用 'TypedArray' 时没有使用 'try-with-resources' 语句”。如何解决此警告?

TypedArray attributes = context.obtainStyledAttributes(
            attrs, R.styleable.RVIndicator, defStyleAttr, R.style.RVIndicator);
1个回答

5

TypedArray 实现了 AutoClosable 接口,这意味着您可以像这样使用它在 try-with-resources 中:

try (TypedArray attributes = context.obtainStyledAttributes(
            attrs, R.styleable.RVIndicator, defStyleAttr, R.style.RVIndicator)) {
    dotColor = attributes.getColor(R.styleable.RVIndicator_dotColor, 0);
    // rest of your code using attributes
    visibleDotThreshold = 0;
    // notably *no* call to attributes.recycle()
    // the try-with-resources makes sure that close() is called
}

这可以确保即使在代码块中发生异常,TypedArray也能被正确回收/关闭。

值得注意的是,TypedArray.close() 实际上调用了 recycle()。另外,从 API 31 (S) 开始才支持 try-with-resources。 - Matthieu
1
值得注意的是,TypedArray.close() 实际上调用了 recycle() 方法。另外,需要注意的是,使用 try-with-resources 语法只能在 API 31 (S) 及以上版本中使用。 - Matthieu
8
那么,对于 API < 31,我需要做什么呢? - ProjectDelta
@ProjectDelta 使用完后,只需调用recycle()函数即可。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接