- android.widget.BaseAdapter 적용
- ViewHolder 방식 사용
1. BaseAdapter 구현
public class TextListAdapter extends BaseAdapter {
private LayoutInflater inflater;
static class Holder {
private final TextView text;
public Holder(View itemView) {
this.text = itemView.findViewById(android.R.id.text1);
}
void bindData(String item) {
text.setText(item);
}
}
private final ArrayList<String> contentItems = new ArrayList<>();
@Override
public int getCount() {
return contentItems == null ? 0 : contentItems.size();
}
@Override
public String getItem(int position) {
return contentItems != null && position < getCount() ? contentItems.get(position) : null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = LayoutInflater.from(parent.getContext());
Holder holder;
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
holder = new Holder(convertView);
} else {
holder = (Holder) convertView.getTag();
}
holder.bindData(getItem(position));
return convertView;
}
}
- Holder 클래스(ViewHolder)를 View 태그에 넣어서 재활용한다.
- ListView 어뎁터 구현의 가장 기본이 되는 방식.
2. ListView 구현
public class TextListFragment extends Fragment {
public TextListFragment() {
// Required empty public constructor
}
public static TextListFragment newInstance() {
TextListFragment fragment = new TextListFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> items = new ArrayList<>();
items.add("Text Item 1");
items.add("Text Item 2");
items.add("Text Item 3");
View view = inflater.inflate(R.layout.fragment_text_list, container, false);
ListView listView = view.findViewById(R.id.listView);
listView.setAdapter(new TextListAdapter(items));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
if (item instanceof String) {
}
}
});
return view;
}
}
- AdapterView에서 아이템을 가져와 클릭이벤트에 해당하는 아이템을 불러온다.