阅读量:95
getIdentifier() 是 Android 中用于获取资源标识符(如资源 ID)的方法。当处理自定义属性时,您可能需要使用 getIdentifier() 方法来查找和访问这些自定义属性的资源 ID。以下是如何在自定义属性处理器中使用 getIdentifier() 的步骤:
- 首先,确保您的自定义属性已经定义在
res/values/attrs.xml文件中。例如:
<resources>
<declare-styleable name="CustomView">
<attr name="customColor" format="color" />
<attr name="customText" format="string" />
</declare-styleable>
</resources>
- 在自定义视图的构造函数中,使用
TypedArray获取自定义属性的值。例如:
public class CustomView extends View {
private int customColor;
private String customText;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customColor = typedArray.getColor(R.styleable.CustomView_customColor, Color.BLACK);
customText = typedArray.getString(R.styleable.CustomView_customText, "Default Text");
typedArray.recycle();
}
}
在这个例子中,我们使用 getIdentifier() 方法从 TypedArray 中获取自定义属性的值。注意,我们需要传递属性的名称(如 R.styleable.CustomView_customColor)而不是直接传递资源的 ID。这是因为 getIdentifier() 方法会根据属性名称查找相应的资源 ID。
- 现在,您可以在自定义视图中使用这些自定义属性的值,例如设置颜色或文本。
请注意,getIdentifier() 方法可能会返回 -1,如果找不到指定的资源。因此,在使用返回的资源 ID 之前,请检查其值是否为 -1。