我用这段代码测试了TypedArray
recycle,期望根据文档得到运行时异常,但我没有得到。
recycle
added in API level 1
void recycle () Recycles the TypedArray, to be re-used by a later caller. After calling this function you must not ever touch the typed array again.Throws RuntimeException if the TypedArray has already been recycled.
public TimePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TimePickerPreference, 0, 0);
initTimePickerPreference(a);
a.recycle();
}
protected void initTimePickerPreference(TypedArray a) {
if (a != null)
try {
setTitle(a.getString(R.styleable.TimePickerPreference_android_title));
mSummary = a.getString(R.styleable.TimePickerPreference_android_summary);
mDefaultValue = a.getString(R.styleable.TimePickerPreference_android_defaultValue);
} finally {
a.recycle();
}
...
}
我使用 Android Studio 调试器跟踪代码,它经历了两个 a.recycle()
调用,同时在 variables Pane a
未设为 null
我进行此测试的原因是因为我不能 100% 确定在与 a
不同的范围内调用 a.recycle()
是否可以已创建。
我更进一步复制了回收调用
public TimePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TimePickerPreference, 0, 0);
initTimePickerPreference(a);
a.recycle();
a.recycle();
}
protected void initTimePickerPreference(TypedArray a) {
if (a != null)
try {
setTitle(a.getString(R.styleable.TimePickerPreference_android_title));
mSummary = a.getString(R.styleable.TimePickerPreference_android_summary);
mDefaultValue = a.getString(R.styleable.TimePickerPreference_android_defaultValue);
} finally {
a.recycle();
a.recycle();
}
...
}
仍然没有RunTimeException
。
这是一个错误吗?
我在 Android IceCreamSandwich 版本 (API 15) 的 AVD 模拟设备上运行它。
最佳答案
Here's API 15 的 TypedArray#recycle()
实现:
public void recycle() {
synchronized (mResources.mTmpValue) {
TypedArray cached = mResources.mCachedStyledAttributes;
if (cached == null || cached.mData.length < mData.length) {
mXml = null;
mResources.mCachedStyledAttributes = this;
}
}
}
Here's API 25 的实现:
public void recycle() {
if (mRecycled) {
throw new RuntimeException(toString() + " recycled twice!");
}
mRecycled = true;
// These may have been set by the client.
mXml = null;
mTheme = null;
mAssets = null;
mResources.mTypedArrayPool.release(this);
}
显然,文档说明了最新 API 的实现,并且您正在使用 API 15 运行您的应用。
关于android - 测试 TypedArray recycle() 不会抛出 RuntimeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468243/