前言
有時候我們需要根據資源檔案名來獲取整型的資源id,比如我有資源名為ui1~ui13的10張圖片,想通過圖片名稱動態加載某張資源圖片,這時就需要把圖片名稱轉換成圖片資源的id加載圖片,具體可以看代碼更清晰;
第一種實作方式:
點擊一下切換下一張圖片
private int n = 2;
public void click(View view) throws IllegalAccessException {
if (n > 13) {
n = 1;
}
String imgName = "ui" + n;//圖片資源名稱ui1到ui13
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
Drawable drawable = getDrawable(id);
iv_ui.setImageDrawable(drawable);
n++;
}
注意這是通過getIdentifier(String name, String defType, String defPackage) 獲取圖片資源ID,defType還可以是string,raw,color,layout等;
第二種
private int m = 2;
public void click(View view) throws IllegalAccessException {
if (m > 13) {
m = 1;
}
String imgName = "ui" + m;
Drawable drawable = getDrawable(getImageResourceId(imgName));
iv_ui.setImageDrawable(drawable);
m++;
}
private int getImageResourceId(String name) {
//默認的id
int resId = 2131165336;
try {
//根據字串欄位名,取欄位//根據資源的ID的變數名獲得Field的物件,使用反射機制來實作的
java.lang.reflect.Field field = R.drawable.class.getField(name);
//取值
resId = (Integer) field.get(R.drawable.class);
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
這里使用的是反射,通過可以反射string,raw ,color等資源id;
第三種
當然如果還可以通過陣列的方式實作點擊回圈切換圖片的功能,把所有圖片id放到陣列中,通過所以來獲取圖片資源ID同樣可以實作;
private int i = 0;
int[] ids = {R.drawable.ui1, R.drawable.ui2, R.drawable.ui3, R.drawable.ui4, R.drawable.ui5,R.drawable.ui6, R.drawable.ui7, R.drawable.ui8, R.drawable.ui9, R.drawable.ui10,R.drawable.ui11, R.drawable.ui12, R.drawable.ui13};
public void click(View view) {
if (i >= 13) {
i = 0;
}
int drawableId = ids[i];
iv_ui.setImageResource(drawableId);
i++;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/287178.html
標籤:其他
