이것저것/My_Work

[안드로이드] - 리소스 아이디가 바뀔경우 참고

우담바라 2015. 7. 10. 16:42

라이브러리로 배포 할경우, 라이브러리에서 사용하는 리소스 파일의 아이디가 변경이 된다.

이때 아래 내용을 참고.


참고 http://codemanteau.com/blog/blog_72


Sometimes, we need to get a resource from the Android resource library without knowing its name. Perhaps we have R.id.data1 through R.id.data9 and want to fetch all 9 of them without hardcoding each one.

This has been possible since API 1, through the use of getIdentifier(). I will start off by saying that this is not as efficient as referencing R, so it should be used ONLY in the event that you cannot be sure of the ID you are fetching.

The usage is actually quite easy; let's say we have nine TextViews that we want to change to the text "Foo 1" through "Foo 9". Their IDs are R.id.text1 through R.id.text9.

Java
  1. for (int i = 1; i <= 9; i++) {
  2. // This has to be called from somewhere we can access getResources() and getPackageName().
  3. // If we cannot access those, we need a Context, from which we can call context.getResources() and context.getPackageName().
  4. int myTextId = getResources().getIdentifier("text"+i, "id", getPackageName());
  5. TextView myText = (TextView) findViewById(myTextId);
  6. textInfo.setText("Foo "+i);
  7. }