android - Android应用中TypedArray的使用

标签 android

我在

遇到了代码

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>

  1. 我可以知道他们为什么需要从 XML 中获取整数值吗?他们为什么不直接编码 mGalleryItemBackground = 0;mTileSize = 12;?我的猜测是,他们希望能够在不接触 Java 代码的情况下进行更改。但是,我没有看到在 XML 文件本身中明确指定了任何值。 非常感谢演示 TypedArray 和 context.obtainStyledAttributes 用途的代码示例。
  2. 两者都在尝试读取整数。为什么一个例子使用 getResourceId 技术,另一个使用 getInt 技术?
  3. 我引用 TypedArray JavaDoc ,但我很难理解 recycle 是做什么的?

Give back a previously retrieved StyledAttributes, for later re-use.

最佳答案

  1. 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 中读取可能很有用...您可能需要不同大小的磁贴用于不同的密度+尺寸组合。

  1. Both are trying to read an integer. Why one of the example is using getResourceId technique, another is using getInt technique?

因为画廊背景不是整数......它应该是一个资源标识符(例如@drawable/foo)。是的,它 仍然是一个整数,但它的值直到运行时才知道的整数。相比之下,图 block 大小是一个常数值,不需要任何类型的运行时解析。

  1. 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/

相关文章:

android - ExoPlayer 2 迁移

java - 组织.json.JSONException : Unterminated string at character 1834

android - 如何将 VectorDrawable 与 Android 工具栏一起使用?

android - notifyDataSetChanged 与 notifyItemInserted

android - GSON:期望一个字符串,但是是 BEGIN_OBJECT?

android - sqlite 表中的每一行如何是唯一的。不仅仅是一列行

android - 如何使我的应用程序成为辅助应用程序设置中的一个选项?

Android 从客户端获取 http 请求

android - 在 OpenSL ES 记录器对象上请求接口(interface) SL_IID_ANDROIDSIMPLEBUFFERQUEUE 返回 SL_RESULT_FEATURE_UNSUPPORTED

java - 如何访问try-catch中的变量?