Android lint 会警告在未使用“try”-with-resources 语句的情况下使用“TypedArray”。怎么解决呢?

Cha*_*kar 3 android lint

我有以下代码:

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于以下语句 lint 给出警告“TypedArray”在没有“try”-with-resources 语句的情况下使用”。如何解决这个警告?

TypedArray attributes = context.obtainStyledAttributes(
            attrs, R.styleable.RVIndicator, defStyleAttr, R.style.RVIndicator);
Run Code Online (Sandbox Code Playgroud)

Joa*_*uer 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
}
Run Code Online (Sandbox Code Playgroud)

这保证了TypedArray即使在该代码块中发生某些异常时也能正确回收/关闭。

  • 那么对于 API < 31 我需要做什么? (9认同)