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。