在制作Cordova插件時(shí)不能通過(guò)R文件來(lái)尋找資源Id,因?yàn)镽文件是不斷變化的,所以我們必須要通過(guò)資源名稱來(lái)獲取Id,下面就介紹一下資源id的獲取:
- 使用Resources 類的 getIdentifier方法
-
通過(guò)資源名稱虛招布局文件的id
private int getResId(String resourceName){ Resources resources = getResources(); int resId = resources.getIdentifier(resourceName,"layout",getPackageName()); return resId; }
-
獲取字符串id
private int getStringId(String stringName){ Resources resources = getResources(); int resId =resources.getIdentifier(stringName,"string", getPackageName()); return resId; }
-
獲取控件id
private int getId(String idName){ Resources resources = getResources(); int resId = resources.getIdentifier(idName, "id", getPackageName()); return resId; }
-
獲取動(dòng)畫id
private int getAnimId(String idName){ Resources resources = getResources(); int resId = resources.getIdentifier(idName, "anim", getPackageName()); return resId; }
-
作為一個(gè)Android開發(fā)者來(lái)說(shuō),也許你已經(jīng)發(fā)現(xiàn)上面代碼的不同點(diǎn)了,就是getIdentifier()里面的第二個(gè)參數(shù)的不同,我們可以通過(guò)替換這個(gè)參數(shù)來(lái)達(dá)到大部分的尋找資源id(example:id, string, anim, attr, drawable, layout, color, menu, styles...)
- 通過(guò)Java的強(qiáng)大的反射機(jī)制獲取資源id
-
通過(guò)反射獲取一個(gè)資源id
public int getAttrId(String attrName) { try { Class<?> loadClass = mContext.getClassLoader().loadClass(mContext.getPackageName() + ".R"); Class<?>[] classes = loadClass.getClasses(); for (int i = 0; i < classes.length; i++) { if (classes[i].getName().equals(mContext.getPackageName() + ".R$attr")) { Field field = classes[i].getField(attrName); int attrId = field.getInt(null); return attrId; } } } catch (Exception e) { e.printStackTrace(); } return 0; }
-
首先使用反射能達(dá)到上面的獲取一個(gè)id的情況,但是比較麻煩,當(dāng)需要返回一個(gè)數(shù)組我們就不得不使用這種方法了
private int[] getStyleableArryId(String styleableName){ try { Class<?> loadClass = getContext().getClassLoader().loadClass(getContext().getPackageName() + ".R"); Class<?>[] classes = loadClass.getClasses(); for(int i=0 ;i<classes.length ;i++){ Class<?> resClass = classes[i]; if(resClass.getName().equals(getContext().getPackageName() + ".R$styleable")){ Field[] fields = resClass.getFields(); for (int j = 0; j < fields.length; j++) { if(fields[j].getName().equals(styleableName)){ int[] styleable = (int[]) fields[j].get(null); return styleable; } } } } } catch (Exception e) { e.printStackTrace(); } return null; }
-
但是在設(shè)置styleable的資源id的時(shí)候,如果你是自定義的View,如果需要引入自定義的attr,比如這樣:
public WheelVerticalView(Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.abstractWheelViewStyle);
this(context, attrs, 0);
}