android

[Android]문자열로 resource ID값 가져오기

포카리s 2017. 11. 22. 22:31
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안드로이드를 개발할때 테이블 화면 같이 여러 셀들을 만들다 보면

리소스 아이디 관리 하기가 귀찮아 질때가 많다 

그럴때 유용하게 사용 하면 될듯 하다


xml화면은 똑같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<TextView
            android:id="@+id/tv_frag_timespread_1_1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_5"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_6"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv_frag_timespread_1_7"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

cs


자바 클래스에서
1
2
3
4
5
6
7
8
9
10
11
12
13
텍스트뷰를 담을 배열 선언
 private TextView[][] tv = new TextView[13][7];
 
포문을 사용 하여 아이디값을 가져온 다음 배열에 담아준다.
for(int i=0; i<tv.length; i++){
    for(int k=0;k<tv[i].length;k++){
        getID=act.getRessources().getIdentifier("tv_frag_timespread_"+(i+1)+"_"+(k+1),"id",act.getPackageName());
        tv[i][k]=(TextView)view.findViewById(getID);
        tv[i][k].setText(String.valueOf(i)+String.valueOf(k));
    }
}
 
 
cs

여기서 주목해서 봐야 할 코드는
getRessources().getIdentifier("tv_frag_timespread_"+(i+1)+"_"+(k+1),"id",act.getPackageName());
이 코드 이다.