안드로이드 개발 질문/답변
(글 수 45,052)
ListView에 custom하게 뿌리는데요
이번에는 ListView에 레이아웃이 여러가지를 써야됩니다.
listA.xml
listB.xml
이런식으로 레이아웃 파일을 두가지로 만든다고하면 (두개가 모양이 완전달라서요 )
public class CustomNewsList extends BaseAdapter {
int layoutA;
int layoutB;
public CustomNewsList(Context context,int layoutA,int layoutB,ArrayList<String> list){
뭐 생성자에서 A,B에 레이아웃 값을 받게 되어있는데요.
문제는
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(layoutA,parent,false);
}
이런식으로 레이아웃을 가져올때 A,B를 순차적으로 if else 로 선택하게 하면되겠지만
그 Holder pattern을 안드로이드 API에서는 권장한다고 (뭐 성능상 어쩌고..) 했는데 이렇게 다중 레이아웃에서는 어떤식으로 쓰나요?
단일 레이아웃 에서 홀더 패턴은 API데모에서 보면 아래처럼 샘플이 있는데 이걸 다중 레이아웃으로 어떻게 바꿔야될지 잘모르겠네요.
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}




이게 좀 난감한데요...
뷰 재활용 때문에 넘어오는 것이 꼭 같은 종류라고 보장 할 수 없습니다.
약간 속도의 손해를 봐야 할 거 같습니다.
클래스 ViewHolder1과 ViewHolder2를 만들고
convertView가 null이 아닌 경우
holder를 받아서 현재 Position에 맞는 holder인지 확인(instanceof 연산...)하고
맞으면 그대로 쓰시고 아니면 새 holder 만들어서 쓰시고.... 어쩔수 없을거 같습니다.
공통부분을 뽑아서 쓸수 없다면 말이죠...