Android资源ID

问题描述 投票:50回答:3

我正在从自定义xml视图类型检索自定义资源ID。我被要求为检索指定默认的int值,并且想知道ID的范围是多少?他们总是积极的还是包括零?

即是-1是有效的“空”引用,并且/或者是0是有效的“空”引用?

谢谢

编辑

自定义XML资源/属性文件

<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="onImage" format="integer" />
        <attr name="offImage" format="integer" />
    </declare-styleable>
</resources>

在我的自定义用户界面的构造函数中定义

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);

int offResource = a.getInt(R.styleable.ToggleImageButton_offImage, -1);

基本上,第二行末尾的-1是此数据类型的默认参数。开发时可以在XML视图中初​​始化它,也可以不初始化它,这允许以这种方式指定默认行为。

android resources
3个回答
84
投票

根据the documentation, Resources.getIdentifier()

如果没有这样的资源,则返回0 被找到。 (0不是有效的资源ID。)

所以您可以使用0。


9
投票

0是资源ID的空/无效值。


0
投票

根据Resources.getIdentifier()https://developer.android.com/reference/android/content/res/Resources#ID_NULL与在XML中设置0相同,这意味着您可以使用它,即,当您想要清除资源时。

这是无效的资源ID。

© www.soinside.com 2019 - 2024. All rights reserved.