ArrayAdapter 관해서 질문드립니다.

조회수 4617회
adapter = new ArrayAdapter<InspectorItem>
                (this, R.layout.test_list, strs);

위 코드로 실행 했을 경우에는 ArrayAdapter requires the resource ID to be a TextView 라는 에러가 발생합니다.

adapter = new ArrayAdapter<InspectorItem>
                (this, R.layout.test_list, R.id.testItem, strs);

그래서 파라미터에 testItem 이라는 리스트뷰에 들어갈 row의 id를 추가해주니 에러가 안났습니다. testItem 은 TextView 입니다. 왜 넣어야 하는지 감은 오나 명확한 이유를 모르겠습니다.

1 답변

  • 좋아요

    2

    싫어요
    채택 취소하기

    ArrayAdapter는 배열 항목을 기본적으로 TextView로 결과를 표시하도록 되었습니다. 대상 레이아웃이 TextView 외에도 여러가지가 있을 경우(혹은 레이아웃에 뷰가 포함된 경우도 같음), 어느 뷰에 표시해야 될지 알 수 없어서 발생하는 에러입니다.

    해결하려면...

    1. 질문하신 예처럼 대상 레이아웃 내에서 배열항목을 출력할 수 있는 TextView의 id를 지정해주거나,
    2. ArrayAdapter의 getView 함수를 다시 오버라이드 해서 구현해야 합니다. 다음 예시를 참고하세요. (아래 예시처럼 두 개 이상의 뷰에 적용하고자 경우는 오버라이드 해야만 합니다.)

    예시 : res/layout/item.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >
        <TextView
          android:id="@+id/name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Name" />
       <TextView
          android:id="@+id/email"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Email" />
    </LinearLayout>
    

    예시: CardAdapter.java

    public class CardAdapter extends ArrayAdapter<Card> {
        public CardAdapter(Context context, ArrayList<Card> cards) {
           super(context, 0, cards);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           // 배열에서 position에 위치한 데이터(아이템) 가져오기
           Card card = getItem(position);    
           // 아이템의 내용을 그림 convertView의 재사용을 위해서 확인
           // null 이면 새로 만들고, null 이 아니면 재사용한다.
           if (convertView == null) {
              convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
           }
           // ConvertView에서 Card의 내용을 적용할 뷰 찾기
           TextView name = (TextView) convertView.findViewById(R.id.name);
           TextView email = (TextView) convertView.findViewById(R.id.email);
           // 뷰에 값 지정하기.
           name.setText(card.name);
           email.setText(card.email);
           // 완성된 뷰를 반환 ( 화면에 보여주게 된다. )
           return convertView;
       }
    }
    
    • 감사합니다 ^^ 김선우 2016.3.15 10:58

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)