2019년 6월 7일 금요일

안드로이드 RecyclerView 예제

- RecyclerView.ViewHolder 적용
- androidx.recyclerview.widget.DiffUtil 적용


1. RecyclerView.Adapter 구현
public class TextRecyclerAdapter extends RecyclerView.Adapter<TextRecyclerAdapter.Holder> {
    private LayoutInflater inflater;
    private final ArrayList<String> items = new ArrayList<>();

    public void updateList(final List<String> newItems) {
        TextDiff callback = new TextDiff(this.items, newItems);
        DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
        this.items.clear();
        this.items.addAll(newItems);
        result.dispatchUpdatesTo(this);
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (inflater == null)
            inflater = LayoutInflater.from(parent.getContext());

        View itemView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
        return new Holder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        holder.bindData(getItem(position));

    }

    public String getItem(int position) {
        return items != null && position < getItemCount() ? items.get(position) : null;
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }

    static class Holder extends RecyclerView.ViewHolder {
        private final TextView text;

        public Holder(@NonNull View itemView) {
            super(itemView);
            this.text = itemView.findViewById(android.R.id.text1);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object tag = v.getTag();
                    if (tag instanceof String) {

                    }
                }
            });
        }

        public void bindData(String item) {
            itemView.setTag(item);
            if (item == null)
                return;
            text.setText(item);
        }
    }

    static class TextDiff extends DiffUtil.Callback {
        private final List<String> oldItems;
        private final List<String> newItems;

        public TextDiff(List<String> oldItems, List<String> newItems) {
            this.oldItems = oldItems;
            this.newItems = newItems;
        }

        @Override
        public int getOldListSize() {
            return oldItems.size();
        }

        @Override
        public int getNewListSize() {
            return newItems.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            if (oldItemPosition > newItemPosition)
                return false;
            return oldItems.get(oldItemPosition).equals(newItems.get(oldItemPosition));
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            if (oldItemPosition > newItemPosition)
                return false;
            return oldItems.get(oldItemPosition).equals(newItems.get(oldItemPosition));
        }
    }
}


- ViewHolder 클래스를 구현해서 사용한다.
- DiffUtil 클래스를 구현해서 리스트 갱신을 효율적으로 구현한다.






2. RecyclerView 구현
public class RecyclerListFragment extends Fragment {

    public RecyclerListFragment() {
        // Required empty public constructor
    }

    public static RecyclerListFragment newInstance() {
        RecyclerListFragment fragment = new RecyclerListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recycler_list, container, false);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(recyclerView.getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        TextRecyclerAdapter textRecyclerAdapter = new TextRecyclerAdapter();
        recyclerView.setAdapter(textRecyclerAdapter);

        ArrayList<String> items = new ArrayList<>();
        items.add("Text Item 1");
        items.add("Text Item 2");
        items.add("Text Item 3");
        textRecyclerAdapter.updateList(items);

        return view;
    }
}


- updateList를 호출하면 DiffUtil 기능으로 리스트가 자연스럽게 갱신된다.

안드로이드 BaseAdapter 예제

- 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에서 아이템을 가져와 클릭이벤트에 해당하는 아이템을 불러온다.