개발일지/빅데이터 댓글 시각화 프로젝트

[개발일지] for문으로 xml resource 가져오기(feat.getIdentifier())

Emil :) 2020. 12. 10. 13:55
728x90
반응형
이 글은 Notion에서 작성 후 재편집한 포스트입니다.

목차

 

오늘의 목표


  1. for문으로 xml resource 가져오기

참고


okky.kr/article/819296?note=2151849

 

OKKY | 안드로이드 for문으로 변수 값 넣어주기 관련 질문입니다.

안녕하세요, 다음과 같이 선언되있는 UI에 for문으로 데이터를 집어넣고 싶습니다. ImageView simArticleImg1 view.findViewById(R.id. simArticleImg1 ) ; TextView simArticleTitle1 view.findViewById(R.id. simArticleTitle1 ) ; Tex

okky.kr

내 질문임 ㅋㅅㅋ

진행 과정


for문으로 xml resource 가져오기


현재 내가 작업하고자 하는 xml은 아래 화면과 같다.

이를 xml코드로 나타내면 다음과 같다. 같은 코드가 반복되므로 3개까지만 쓰겠다.

<RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
	<TextView
                        android:id="@+id/posBestCommId1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="ID"
                        android:textSize="20dp"
                        android:layout_marginTop="10dp"
                        android:layout_marginLeft="10dp"/>
	<TextView
                        android:id="@+id/posBestCommCon1"
                        android:layout_below="@id/posBestCommId1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="테\n스\n트\n입\n니\n다\n"
                        android:textSize="15dp"
                        android:layout_margin="10dp"/>
	<RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/posBestCommCon1">
		<TextView
                            android:id="@+id/posBestCommDisLike1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="비추 수"
                            android:layout_alignParentRight="true"
                            android:layout_marginRight="20dp"
                            />
		<TextView
                            android:id="@+id/posBestCommLike1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="30dp"
                            android:layout_toLeftOf="@+id/posBestCommDisLike1"
                            android:text="따봉 수" />
		<ImageView
                            android:id="@+id/posBestCommLikeImg1"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommLike1"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_up_black_24dp"/>
		<ImageView
                            android:id="@+id/posBestCommDisLikeImg1"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommDisLike1"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_down_black_24dp"/>
	</RelativeLayout>
</RelativeLayout>
<RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
	<TextView
                        android:id="@+id/posBestCommId2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="ID"
                        android:textSize="20dp"
                        android:layout_marginTop="10dp"
                        android:layout_marginLeft="10dp"/>
	<TextView
                        android:id="@+id/posBestCommCon2"
                        android:layout_below="@+id/posBestCommId2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="테\n스\n트\n입\n니\n다\n"
                        android:textSize="15dp"
                        android:layout_margin="10dp"/>
	<RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/posBestCommCon2">
		<TextView
                            android:id="@+id/posBestCommDisLike2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="비추 수"
                            android:layout_alignParentRight="true"
                            android:layout_marginRight="20dp"
                            />
		<TextView
                            android:id="@+id/posBestCommLike2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="30dp"
                            android:layout_toLeftOf="@+id/posBestCommDisLike2"
                            android:text="따봉 수" />
		<ImageView
                            android:id="@+id/posBestCommLikeImg2"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommLike2"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_up_black_24dp"/>
		<ImageView
                            android:id="@+id/posBestCommDisLikeImg2"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommDisLike2"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_down_black_24dp"/>
	</RelativeLayout>
</RelativeLayout>
<RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
	<TextView
                        android:id="@+id/posBestCommId3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="ID"
                        android:textSize="20dp"
                        android:layout_marginTop="10dp"
                        android:layout_marginLeft="10dp"/>
	<TextView
                        android:id="@+id/posBestCommCon3"
                        android:layout_below="@+id/posBestCommId3"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="테\n스\n트\n입\n니\n다\n"
                        android:textSize="15dp"
                        android:layout_margin="10dp"/>
	<RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/posBestCommCon3">
		<TextView
                            android:id="@+id/posBestCommDisLike3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="비추 수"
                            android:layout_alignParentRight="true"
                            android:layout_marginRight="20dp"
                            />
		<TextView
                            android:id="@+id/posBestCommLike3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="30dp"
                            android:layout_toLeftOf="@+id/posBestCommDisLike3"
                            android:text="따봉 수" />
		<ImageView
                            android:id="@+id/posBestCommLikeImg3"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommLike3"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_up_black_24dp"/>
		<ImageView
                            android:id="@+id/posBestCommDisLikeImg3"
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_toLeftOf="@id/posBestCommDisLike3"
                            android:layout_centerVertical="true"
                            android:src="@drawable/ic_thumb_down_black_24dp"/>
	</RelativeLayout>
</RelativeLayout>

코드를 살펴보면, id1, id2, id3 이런식으로 뒤에 숫자만 붙이는 식으로 늘이는 것을 확인할 수 있다.
사실 이 xml도 가장 좋은방법은 customView를 만들어서 xml코드를 줄이는 것이다.

gun0912.tistory.com/38

 

[안드로이드/Android]CustomView를 만들어서 재사용하기

이전 포스팅에서 Style테마를 이용하여 일정한 레이아웃의 속성을 만들고 이를 재사용하는 방법에 대해서 알아 보았습니다. [안드로이드]style테마 활용으로 노가다코딩 줄이는 방법 이 방법보다

gun0912.tistory.com

해당 사항은 위 포스팅을 참조하도록 하자, 굉장히 정리가 잘 되어있다. 아무튼 이런식으로 반복된 코드가 있다.

이제 자바코드를 살펴보도록 하자.
가장 기본적인 방법으로 접근한다면, 아마 이런식으로 resource id 를 가져올 것이다.

TextView posBestCommId1 = view.findViewById(R.id.posBestCommId1);
TextView posBestCommCon1 = view.findViewById(R.id.posBestCommCon1);
ImageView posBestCommLikeImg1 = view.findViewById(R.id.posBestCommLikeImg1);
ImageView posBestCommDisLikeImg1 = view.findViewById(R.id.posBestCommDisLikeImg1);
TextView posBestCommLike1 = view.findViewById(R.id.posBestCommLike1);
TextView posBestCommDisLike1 = view.findViewById(R.id.posBestCommDisLike1);

TextView posBestCommId2 = view.findViewById(R.id.posBestCommId2);
TextView posBestCommCon2 = view.findViewById(R.id.posBestCommCon2);
ImageView posBestCommLikeImg2 = view.findViewById(R.id.posBestCommLikeImg2);
ImageView posBestCommDisLikeImg2 = view.findViewById(R.id.posBestCommDisLikeImg2);
TextView posBestCommLike2 = view.findViewById(R.id.posBestCommLike2);
TextView posBestCommDisLike2 = view.findViewById(R.id.posBestCommDisLike2);

TextView posBestCommId3= view.findViewById(R.id.posBestCommId3);
TextView posBestCommCon3 = view.findViewById(R.id.posBestCommCon3);
ImageView posBestCommLikeImg3 = view.findViewById(R.id.posBestCommLikeImg3);
ImageView posBestCommDisLikeImg3 = view.findViewById(R.id.posBestCommDisLikeImg3);
TextView posBestCommLike3 = view.findViewById(R.id.posBestCommLike3);
TextView posBestCommDisLike3 = view.findViewById(R.id.posBestCommDisLike3);
.
.
.

... 시각을 포기한다

아무튼 이런 코드는 정말 효율이 안좋다. 나중에 바꾸기도 힘들고..
그래서 있는게 getresource의 getIdentifier 메서드이다.

안드로이드 공식문서에 다음과 같이 나와있다.

developer.android.com/reference/android/content/res/Resources

 

Resources  |  Android 개발자  |  Android Developers

 

developer.android.com

getResources().getIdentifier(이름, 타입, 패키지명) 형태로 사용된다.

이름 : 본인이 id에 할당한 이름
타입 : 무엇을 통해 찾을건지 (ex. id)
패키지명 : 패키지명을 써주면 된다.

이제 이걸 맵핑시키는 작업을 해보자.
나는 emotionCommentArrayLIst 라는 애가 있다. 다음과 같이 위에 선언되어있다.
이 ArrayList는 Hashmap<String, String> 형태로 되어있다.

ArrayList<HashMap> emotionCommentsArrayList;

그리고 현재 이 예제를 작성하는 곳은 activity가 아니라 fragment 이다.

따라서, getActivity().getPackageName() 을 통해 패키지명을 가져와줘야 한다.
각설하고, 코드로 한눈에 알아볼 수 있도록 하자.

TextView[] commId = new TextView[emotionCommentsArrayList.size()];
TextView[] commCon = new TextView[emotionCommentsArrayList.size()];
TextView[] commLike = new TextView[emotionCommentsArrayList.size()];
TextView[] commDislike = new TextView[emotionCommentsArrayList.size()];

int cnt = 0;

//긍정 댓글 탑 5 뽑기
for(int i = 0; i < emotionCommentsArrayList.size(); i++){
    if(cnt == 5)
        break;
    if(emotionCommentsArrayList.get(i).get("emotionBool").toString().equals("1")){
        String usrName = emotionCommentsArrayList.get(i).get("usrName").toString();
        String comments = emotionCommentsArrayList.get(i).get("comments").toString();
        String sympathyCount = emotionCommentsArrayList.get(i).get("sympathyCount").toString();
        String antipathyCount = emotionCommentsArrayList.get(i).get("antipathyCount").toString();

        int id = getResources().getIdentifier("posBestCommId" + (i+1), "id", getActivity().getPackageName());
        int con = getResources().getIdentifier("posBestCommCon" + (i+1), "id", getActivity().getPackageName());
        int like = getResources().getIdentifier("posBestCommLike" + (i+1), "id", getActivity().getPackageName());
        int dislike = getResources().getIdentifier("posBestCommDisLike" + (i+1), "id", getActivity().getPackageName());

        commId[i] = view.findViewById(id);
        commCon[i] = view.findViewById(con);
        commLike[i] = view.findViewById(like);
        commDislike[i] = view.findViewById(dislike);
				//여기까지가 resource를 세팅하는 구간의 끝이다. 아래는 여기에 값을 넣어주는 코드다.

        if(commId[i] == null)
            break;
        commId[i].setText(usrName);
        commCon[i].setText(comments);
        commLike[i].setText(sympathyCount);
        commDislike[i].setText(antipathyCount);
        cnt++;
    }
    else {
        continue;
    }
}

주석에 쓴 것처럼, resource를 구성하는 곳은 위에서 끝난다.
getIdentifier를 통해 가져와지는 값들은 모두 int 형, 즉 id값으로 가져와진다. 따라서 findViewById에 이 id값을 넣어주면 된다.

한마디로, 기존에 쓰던 방식과 비교하자면..

int id = getResources().getIdentifier("posBestCommId" + (i+1), "id", getActivity().getPackageName());
commId[i] = view.findViewById(id);

이 코드가

TextView posBestCommId1 = view.findViewById(R.id.posBestCommId1);

이 코드와 상응하는 것이다.

물론 지금엔 텍스트뷰가 5개밖에 없어서 큰 차이가 안날수 있지만..
10개? 100개? 이수준으로 넘어가는데 일일이 이걸 복붙할수는 없지않은가

그리고 만약에 거기서 수정사항이 생긴다? 바로 한강가는거다. ㄹㅇㅋㅋ
아무튼 이런식으로 xml에 있는 resource들을 가져와 할당해주는 방식을 사용하면 된다.

이렇게 해야 코드의 길이도 확 줄어들고, 보기도 좋아진다.

오늘의 결과


TextView posBestCommId1 = view.findViewById(R.id.posBestCommId1);
TextView posBestCommCon1 = view.findViewById(R.id.posBestCommCon1);
ImageView posBestCommLikeImg1 = view.findViewById(R.id.posBestCommLikeImg1);
ImageView posBestCommDisLikeImg1 = view.findViewById(R.id.posBestCommDisLikeImg1);
TextView posBestCommLike1 = view.findViewById(R.id.posBestCommLike1);
TextView posBestCommDisLike1 = view.findViewById(R.id.posBestCommDisLike1);

TextView posBestCommId2 = view.findViewById(R.id.posBestCommId2);
TextView posBestCommCon2 = view.findViewById(R.id.posBestCommCon2);
ImageView posBestCommLikeImg2 = view.findViewById(R.id.posBestCommLikeImg2);
ImageView posBestCommDisLikeImg2 = view.findViewById(R.id.posBestCommDisLikeImg2);
TextView posBestCommLike2 = view.findViewById(R.id.posBestCommLike2);
TextView posBestCommDisLike2 = view.findViewById(R.id.posBestCommDisLike2);

TextView posBestCommId3= view.findViewById(R.id.posBestCommId3);
TextView posBestCommCon3 = view.findViewById(R.id.posBestCommCon3);
ImageView posBestCommLikeImg3 = view.findViewById(R.id.posBestCommLikeImg3);
ImageView posBestCommDisLikeImg3 = view.findViewById(R.id.posBestCommDisLikeImg3);
TextView posBestCommLike3 = view.findViewById(R.id.posBestCommLike3);
TextView posBestCommDisLike3 = view.findViewById(R.id.posBestCommDisLike3);

TextView posBestCommId4 = view.findViewById(R.id.posBestCommId4);
TextView posBestCommCon4 = view.findViewById(R.id.posBestCommCon4);
ImageView posBestCommLikeImg4 = view.findViewById(R.id.posBestCommLikeImg4);
ImageView posBestCommDisLikeImg4 = view.findViewById(R.id.posBestCommDisLikeImg4);
TextView posBestCommLike4 = view.findViewById(R.id.posBestCommLike4);
TextView posBestCommDisLike4 = view.findViewById(R.id.posBestCommDisLike4);

TextView posBestCommId5 = view.findViewById(R.id.posBestCommId5);
TextView posBestCommCon5 = view.findViewById(R.id.posBestCommCon5);
ImageView posBestCommLikeImg5 = view.findViewById(R.id.posBestCommLikeImg5);
ImageView posBestCommDisLikeImg5 = view.findViewById(R.id.posBestCommDisLikeImg5);
TextView posBestCommLike5 = view.findViewById(R.id.posBestCommLike5);
TextView posBestCommDisLike5 = view.findViewById(R.id.posBestCommDisLike5);

HashMap<String, String> map1 = emotionCommentsArrayList.get(0);
HashMap<String, String> map2 = emotionCommentsArrayList.get(1);
HashMap<String, String> map3 = emotionCommentsArrayList.get(2);
HashMap<String, String> map4 = emotionCommentsArrayList.get(3);
HashMap<String, String> map5 = emotionCommentsArrayList.get(4);

posBestCommId1.setText(map1.get("usrName"));
posBestCommCon1.setText(map1.get("comments"));
posBestCommLike1.setText(map1.get("sympathyCount"));
posBestCommDisLike1.setText(map1.get("antipathyCount"));

posBestCommId2.setText(map2.get("usrName"));
posBestCommCon2.setText(map2.get("comments"));
posBestCommLike2.setText(map2.get("sympathyCount"));
posBestCommDisLike2.setText(map2.get("antipathyCount"));

posBestCommId3.setText(map3.get("usrName"));
posBestCommCon3.setText(map3.get("comments"));
posBestCommLike3.setText(map3.get("sympathyCount"));
posBestCommDisLike3.setText(map3.get("antipathyCount"));

posBestCommId4.setText(map4.get("usrName"));
posBestCommCon4.setText(map4.get("comments"));
posBestCommLike4.setText(map4.get("sympathyCount"));
posBestCommDisLike4.setText(map4.get("antipathyCount"));

posBestCommId5.setText(map5.get("usrName"));
posBestCommCon5.setText(map5.get("comments"));
posBestCommLike5.setText(map5.get("sympathyCount"));
posBestCommDisLike5.setText(map5.get("antipathyCount"));


// 기존에 이 코드가 아래 코드로 변하게된다.

TextView[] commId = new TextView[emotionCommentsArrayList.size()];
TextView[] commCon = new TextView[emotionCommentsArrayList.size()];
TextView[] commLike = new TextView[emotionCommentsArrayList.size()];
TextView[] commDislike = new TextView[emotionCommentsArrayList.size()];

int cnt = 0;

//긍정 댓글 탑 5 뽑기
for(int i = 0; i < emotionCommentsArrayList.size(); i++){
  if(cnt == 5)
      break;
  if(emotionCommentsArrayList.get(i).get("emotionBool").toString().equals("1")){
      String usrName = emotionCommentsArrayList.get(i).get("usrName").toString();
      String comments = emotionCommentsArrayList.get(i).get("comments").toString();
      String sympathyCount = emotionCommentsArrayList.get(i).get("sympathyCount").toString();
      String antipathyCount = emotionCommentsArrayList.get(i).get("antipathyCount").toString();

      int id = getResources().getIdentifier("posBestCommId" + (i+1), "id", getActivity().getPackageName());
      int con = getResources().getIdentifier("posBestCommCon" + (i+1), "id", getActivity().getPackageName());
      int like = getResources().getIdentifier("posBestCommLike" + (i+1), "id", getActivity().getPackageName());
      int dislike = getResources().getIdentifier("posBestCommDisLike" + (i+1), "id", getActivity().getPackageName());

      commId[i] = view.findViewById(id);
      commCon[i] = view.findViewById(con);
      commLike[i] = view.findViewById(like);
      commDislike[i] = view.findViewById(dislike);

      if(commId[i] == null)
          break;
      commId[i].setText(usrName);
      commCon[i].setText(comments);
      commLike[i].setText(sympathyCount);
      commDislike[i].setText(antipathyCount);
      cnt++;
  }
  else {
      continue;
  }
}

 

 

--추가

아니.. 나 이거 전에 이미 포스팅했었는데 카테고리가 지정이안되있어서 안보였다.. 하..
어쩐지 쓴 기억이있는데 안보이더라 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ쥐엔장...

구독 및 하트는 정보 포스팅 제작에 큰 힘이됩니다♡

728x90
반응형