본문 바로가기
프로그래밍/DB/JAVA/안드로이드/GAE

[안드로이드] drawable의 리소스를 변수로 가져와 보자

by 아유카와 2013. 3. 28.

   일반적으로 R.drawable.XX 형태로 많이 가져올것이다. 이것을 변수형태로 for문이나 또는 웹에서 받아온 번호의 이미지를 리소스에서 읽어오려면 아래와 같이 하자.


http://www.androidpub.com/index.php?_filter=search&mid=android_dev_qna&search_target=title&search_keyword=drawable&document_srl=2305093


펌 : http://www.androes.com/96

R.drawable내 이미지를 일일히 배열로 지정해서 매칭하는 방법외 가변 변수로 다이나믹하게 지정하는 

방법을 소개해 드릴까 합니다.

예를 들면
 R.drawable.n_1, R.drawable.n_2, R.drawable.n_3 ....R.drawable.n_{n} 의 파일을 호출하고자 할 경우

방법1.

Class<R.drawable> drawable = R.drawable.class;
try {
  Field field;
  for (int m = 0; m <= 10; m++) {
      field = drawable.getField("n_"+m);
  }
  int r;
  r = field.getInt(null);
  ((ImageView)v.findViewById(R.id.iconView)).setImageResource(r);
} catch (Exception e) {}

방법2.
String tmpSign;
for (int m = 0; m <= 10; m++) {
    tmpSign = "n_"+m;
}

// 가변 아이콘을 호출할 경우
int lid = this.getResources().getIdentifier(tmpSign, "drawable", this.getPackageName());
((ImageView)v.findViewById(R.id.iconView)).setImageResource(lid);

// 가변 아이콘을 호출할 경우
int lid = this.getResources().getIdentifier(tmpSign, "string", this.getPackageName());
String str = this.getString(lid); 혹은 this.getResouces().getString(lid);

Document Public Method
int getIdentifier(String name, String defType, String defPackage)
> Return a resource identifier for the given resource name.

첫번째 인자 - 리소스 이름 
두번째 인자 - "string" 같은경우 resource xml 의 element 이름 혹은 "drawable" 로 Drawable도 얻어올수 있다.

============================================================================
TextView tv_nation = (TextView) v.findViewById(R.id.ID_NATION);

int lid = getResources().getIdentifier(xmlData.sign, "string", getPackageName());
tv_nation.setText( lid );    

문자열 표현: getString(lid)
============================================================================
ImageView iv_nationIcon = (ImageView) v.findViewById(R.id.ID_IMG);

String tmpSign = "n_"+xmlData.sign.substring(0, 2).toLowerCase();
int lid = getResources().getIdentifier(tmpSign, "drawable", getPackageName());

iv_nationIcon.setImageResource( lid );