我在
遇到了代码HelloGallery 示例
ImageAdapter.java - http://developer.android.com/resources/tutorials/views/hello-gallery.html
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
attrs.xml - http://developer.android.com/resources/tutorials/views/hello-gallery.html
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HelloGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
还有代码:
贪吃蛇游戏示例
TileView.java - http://developer.android.com/resources/samples/Snake/src/com/example/android/snake/TileView.html
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TileView);
mTileSize = a.getInt(R.styleable.TileView_tileSize, 12);
a.recycle();
attrs.html - http://developer.android.com/resources/samples/Snake/res/values/attrs.html
<resources>
<declare-styleable name="TileView">
<attr name="tileSize" format="integer" />
</declare-styleable>
</resources>
- 我可以知道他们为什么需要从 XML 中获取整数值吗?他们为什么不直接编码
mGalleryItemBackground = 0;
和mTileSize = 12;
?我的猜测是,他们希望能够在不接触 Java 代码的情况下进行更改。但是,我没有看到在 XML 文件本身中明确指定了任何值。 非常感谢演示 TypedArray 和 context.obtainStyledAttributes 用途的代码示例。 - 两者都在尝试读取整数。为什么一个例子使用
getResourceId
技术,另一个使用getInt
技术? - 我引用 TypedArray JavaDoc ,但我很难理解
recycle
是做什么的?
Give back a previously retrieved StyledAttributes, for later re-use.
最佳答案
- May I know why they need to get the integer value from XML? Why don't they just code mGalleryItemBackground = 0; and mTileSize = 12;?
我认为这主要是为了演示从 View 构造函数中读取 XML 属性的技术,而不是满足绝对要求。如果您想在其他地方重新使用您的自定义 View (对于像我承认的 Snake 这样特定的东西不太可能),那么这是一件非常有用的事情......无需更改背景颜色等触摸 Java 代码。
特别是对于磁贴大小,如果不同的设备类型有不同的布局,那么从 XML 中读取可能很有用...您可能需要不同大小的磁贴用于不同的密度+尺寸组合。
- Both are trying to read an integer. Why one of the example is using getResourceId technique, another is using getInt technique?
因为画廊背景不是整数......它应该是一个资源标识符(例如@drawable/foo)。是的,它 是 仍然是一个整数,但它的值直到运行时才知道的整数。相比之下,图 block 大小是一个常数值,不需要任何类型的运行时解析。
- I refer to TypedArray JavaDoc, but I can hardly understand what recycle does?
如有疑问,look at the source .这基本上是一种优化,以避免 LayoutInflater 必须为它膨胀的每个 View 分配其中一个。
关于android - Android应用中TypedArray的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067657/