마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

뷰의 아이디를 문자열 값으로 넘기는 방법

0 추천

TextView txt_value=(TextView)findViewById(R.id.avg);

이런 뷰의 아이디가 여기서는 avg 인데 이걸 문자열로치환해서 할 수 있는 방법이 있나요?

 

예를 들면

 

String str = "avg";

TextView txt_value=(TextView)findViewById(R.id.str);

 

뭐 이런 식으로요. 바로 넘겨서 처리하고 싶습니다. 

지금은 if문으로 

if(str.equals("avg"){

TextView txt_value=(TextView)findViewById(R.id.avg);

}

 

이런 식으로 하다보니 if문이 길어집니다.

 

브루스웨인 (8,580 포인트) 님이 2014년 3월 17일 질문

1개의 답변

+3 추천
 
채택된 답변

Resources 클래스의 getIdentifier라는 메소드가 있습니다.

정의된 이름으로 해당 리소스의 id 값을 찾아오는 메소드 입니다.

 

String name = "avg";
String type = "id";
String package = getPackageName();
int viewId = getResources().getIdentifier(name, type, package);

TextView txt_value=(TextView)findViewById(viewId);

원조안드로이드 (58,190 포인트) 님이 2014년 3월 18일 답변
브루스웨인님이 2014년 7월 19일 채택됨
답변 감사합니다.  궁금한 점이 더 있는데 이미지 파일도 가능한가요?

한번 적용해보았는데 에러가 나긴 합니다만

ImageView position2 = (ImageView)findViewById(R.id.img_position2);//포지션 이미지
        BitmapDrawable img_position = null;
        if(str.equals("ST")){
            img_position = (BitmapDrawable)getResources().getDrawable(R.drawable.st);
            position2.setImageDrawable(img_position);
        }

이러한 소스를

public void setting(String str)
ImageView position = (ImageView)findViewById(R.id.img_position);//포지션 이미지
        BitmapDrawable img_position = null;
        String type = "id";
        String pack = getPackageName();
        int viewId = getResources().getIdentifier(str, type, pack);
        img_position = (BitmapDrawable)getResources().getDrawable(viewId);
        position.setImageDrawable(img_position);

이런식으로 바꿔줬는데 사용하는 함수가 다른거죠?
내가 지정한 뷰의 문자열 아이디를 가져오기
...