实践
页面上有很多结构相同的单元,只是填充的内容不一样,我想通过遍历的方法对每一个单元进行操作。如下操作就可以实现了。是不是很省心。关键点TypedArray。
TypedArray item = getContext().getResources().obtainTypedArray(R.array.guide_template_item);
for (int i = 0; i < Math.min(guideUnits.size(), MAX_COUNT); i++) {
GuideItem guideItem = (GuideItem) findViewById(item.getResourceId(i, 0));
......
}
// 用完之后,记得回收
item.recycle();
在arrays中配置如下:
<array name="guide_template_item">
<item>@id/guide1</item>
<item>@id/guide2</item>
<item>@id/guide3</item>
</array>
TypedArray
Container for an array of values that were retrieved with
{@link Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
or {@link Resources#obtainAttributes}. Be
sure to call {@link #recycle} when done with them.
The indices used to retrieve values from this structure correspond to
the positions of the attributes given to obtainStyledAttributes.
TypedArray是一个容器,这个容器存放的是array的值(看名字也知道了),存放在容器中的这些值使用Resources.Theme下的obtainStyledAttributes和Resources下的obtainAttributes来检索。当完成检索的时候,请调用recycle方法。indices(index复数)用来从对应的容器中检查对应属性的值。所有位置的值可以通过obtainStyledAttributes方法获取到。(obtainStyledAttributes返回TypedArray)
网友评论