안드로이드 개발 질문/답변
(글 수 45,052)
public class Gallery03Activity extends Activity {
....
class ContactsAdapter extends BaseAdapter{
private ArrayList<galleryList> Data;
.........
public View getView (int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(Gallery03Activity.this);
convertView = inflater.inflate(R.layout.gallery_listelement,parent,false);
holder = new ViewHolder(); // static class instance 생성?
holder.txtName = (TextView)convertView.findViewById(R.id.txt_Name);
holder.txtNumber = (TextView)convertView.findViewById(R.id.txt_Number);
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
String name = Data.get(position).toString();
String number = Data.get(position).toString();
holder.txtName.setText(name);
holder.txtNumber.setText(number);
return convertView;
} // getView() Method 부분
} //ContactsAdapter 부분.
static class ViewHolder { // Activity Class의 정적 내부 클래스
TextView txtName;
TextView txtNumber;
}
} // Activity Class 부분
위와 같이 Custom Adapter를 구현하기 위해서 사용한 소스 부분입니다.
여기서 이해가 안가는 부분이 GetView() CallBack 메소드 내부에서 static 클래스의 ViewHolder 인스턴스 생성부분입니다.
holder = new ViewHolder(); // static class instance 생성?
Custom Adapter Class는 instance 타입의 클래스 인데.... ViewHolder는 static 내부 클래스입니다.
이렇게 호출 될때마다 (convertView가 Null인 경우) 새로운 instance를 생성하는게 가능한지 이해가 안가네요.
그리고 굳이... 왜 정적 내부 클래스로 만들었을까요?




우선 내부클래스의 장점은 OOP 개념에서의 캡슐화와 내부, 외부 클래스 사이의 멤버접근에 용이하다는 점입니다.
static 클래스의 특징은 static 멤버나 메쏘드의 경우와 같습니다. 상세히 설명하기에는 댓글로는 무리가 있고, static이 아닌 내부 클래스의 사용에 비해 조금 더 유리하다고 보시면 됩니다. (vm의 메모리 영역과 관련이 있습니다.)
static class instance 생성도 역시 비슷한 맥락이지만, getview에 breakpoint 거시고 직접 참조값을 확인하시는게 좋겠네요. static 클래스라도 내부의 static이 아닌 멤버나 메쏘드의 경우 인스턴스를 생성해야지 접근할 수 있겠죠.. 그렇지 않다면. static 클래스에는 모든 멤버들이 다 static으로 선언되 있어야겠구요....
참고로 드로이드 개발자 페이지에서 구글 i/o(2010년?)세션 중 리스트뷰에 관련한 동영상이 있는데, 한 번 보시는걸 추천드립니다.