0

最近我正在做一个使用Resources.getIdentifier()很多的项目。一切都很有趣,但是当我尝试使用此方法检索自定义属性时会出现问题。

所以我在 xml 中声明了一些属性

<declare-styleable name="WemeFloatExpandMenuItem">
    <attr name="label" format="string|reference"/>
    <attr name="icon" format="reference"/>
    <attr name="showDot" format="boolean"/>
</declare-styleable>

然后我在xml中应用这个属性

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="36dp"
    android:orientation="horizontal"
    android:showDividers="middle"
    android:divider="@drawable/weme_float_menu_divider"
    android:background="@drawable/weme_float_menu_bg">
    <com.weme.chat.FloatExpandMenuItem 
        android:id="@id/wemepay_float_menu_account"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:label="@string/wemepay_float_menu_title_account"
        app:icon="@drawable/weme_float_menu_account"/>

在 FloatExpandMenuItem

TypedArray a = context.obtainStyledAttributes(attrs, ResourceUtils.getResIds(getContext().getPackageName(), "styleable", "WemeFloatExpandMenuItem"));
labelRes = a.getString(ResourceUtils.getResId(getContext(),"styleable","WemeFloatExpandMenuItem_label"));
iconRes = a.getDrawable(ResourceUtils.getResId(getContext(), "styleable", "WemeFloatExpandMenuItem_icon"));
showDot = a.getBoolean(ResourceUtils.getResId(getContext(), "styleable", "WemeFloatExpandMenuItem_showDot"), false);        
a.recycle();

ResourceUtils.getResId 是 Resources.getIdentifier 的包装器,如下所示

public static int getResId(Context context, String resTypeName, String resName) {
    if (context == null) {
        return 0;
    }
    Resources res = context.getResources();
    String packageName = context.getPackageName();
    return res.getIdentifier(resName, resTypeName, packageName);
}

奇怪的事情发生了,我尝试在 FloatExpandMenuItem 中调试,ResourceUtils.getResId 在检索标签、图标、showDot 属性时总是返回 0。

所以我想知道在使用 Resources.getIdentifier() 时尝试处理自定义属性时应该如何更改代码?

4

0 回答 0