티스토리 뷰

RecyclerView

- 새로운 ViewGroup으로 ListView와 GridView의 기능을 제공한다.
- 버전은 support-v7이다.
- 가로 및 세로 레이아웃을 모두 구현할 수 있다.


- RecyclerView.Adapter : 데이터 집합과 view를 연결
- LayoutManager : 아이템들의 위치를 설정하는 기능 제공
- ItemAnimator : 아이템을 추가/제거 혹은 정렬될 때 애니메이션 처리


ListView와의 차이점

 

 RecyclerView

 ListView

ViewHolder 

ViewHolder 패턴을 이용한다.

RecyclerView.Viewholder

ViewHolder 패턴을 이용할 필요가 없다.

 Item Layout

가로/세로/지그재그 방향 모두 지원한다.

RecyclerView.LayoutManager 

세로 방향만 지원한다.

Item Animation 

아이템 애니메이션을 처리하는 클래스가 있다.

RecyclerView.ItemAnimator

아이템이 추가/제거될 때에 적용할 수 있는 애니메이션이 없다. 

 Adapter

데이터를 제공하기 위한 사용자 정의 구현이 필요하다.

RecyclerView.Adapter

배열/DB 결과에 대한 ArrayAdapter/CursorAdapter와 같은 다양한 소스에 대한 어댑터가 존재한다.

Decoration 

RecyclerView.ItemDecoration 객체를 사용하여 더 많은 구분선을 설정해야한다.

android:divider 속성을 이용하여 리스트에 있는 아이템들을 쉽게 구분할 수 있다.

 Click Detection

개별 터치 이벤트를 관리하지만 클릭 처리 기능이 내장되어 있지 않다.

RecyclerView.OnItemTouchListener

목록의 개별 항목에 대한 클릭 이벤트에 바인딩하기 위한 AdapterView.OnItemClickListener 인터페이스가 있다.



예제 실행 화면


예제 코드

1) Data

public class Contact {
    private String mName;
    private boolean mOnline;

    public Contact(String name, boolean online) {
        mName = name;
        mOnline = online;
    }

    public String getName() {
        return mName;
    }

    public boolean isOnline() {
        return mOnline;
    }

    private static int lastContactId = 0;

    public static List createContactsList(int numContacts) {
        List contacts = new ArrayList<>();

        for (int i = 1; i <= numContacts; i++) {
            contacts.add(new Contact("Person " + ++lastContactId, i <= numContacts / 2));
        }

        return contacts;
    }
}

각각의 item들에 들어갈 정보들이 있는 class


2) Adapter

public class ContactsAdapter extends ListAdapter

{ private List mContacts = new ArrayList<>(); public static final DiffUtil.ItemCallback DIFF_CALLBACK = new DiffUtil.ItemCallback() { @Override public boolean areItemsTheSame(Contact oldItem, Contact newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(Contact oldItem, Contact newItem) { return (oldItem.getName() == newItem.getName() && oldItem.isOnline() == newItem.isOnline()); } }; public ContactsAdapter() { super(DIFF_CALLBACK); } public void addMoreContacts(List newContacts) { mContacts.addAll(newContacts); submitList(mContacts); // DiffUtil takes care of the chekc } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View contactView = inflater.inflate(R.layout.item_contact, parent, false); ViewHolder viewHolder = new ViewHolder(contactView); return viewHolder; } @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { Contact contact = getItem(position); TextView textView = viewHolder.nameTextView; textView.setText(contact.getName()); Button button = viewHolder.messageButton; if (contact.isOnline()) { button.setText("Message"); // OMIT to show that rows are recycled. // // Scrolling past the midpoint of the list (when contacts are listed as offline) // and scrolling back up should result in some buttons being inadvertently disabled. button.setEnabled(true); } else { button.setText("Offline"); button.setEnabled(false); } } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView nameTextView; public Button messageButton; public ViewHolder(View itemView) { // Stores the itemView in a public final member variable that can be used // to access the context from any ViewHolder instance. super(itemView); nameTextView = (TextView) itemView.findViewById(R.id.contact_name); messageButton = (Button) itemView.findViewById(R.id.message_button); } } }

- getItemCount > onCreateViewHolder > onBindViewHolder 순서로 실행된다.

- onCreateViewHolder : ViewHolder를 생성

- onBindViewHolder : 만들어진 ViewHolder에 데이터를 넣는 작업

- addMoreContacts : notifyItemRangeInserted를 호출하여 추가적인 정보가 있으면 UI에 반영한다.

3) MainActivity

public class MainActivity extends Activity { ContactsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViews(); } void setupViews() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); // Setup RecyclerView, associated adapter, and layout manager. adapter = new ContactsAdapter(); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // Populate contact list. adapter.addMoreContacts(Contact.createContactsList(20)); // Setup button to append additional contacts. Button addMoreButton = (Button) findViewById(R.id.add_more_contacts); addMoreButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.addMoreContacts(Contact.createContactsList(5)); } }); } }

adapter를 연결해준다.


전체코드는 아래 링크를 통해 볼 수 있습니다.

https://github.com/codepath/fb-recyclerview-demo

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함