기본 콘텐츠로 건너뛰기

[Android] Fragment에 RecyclerView 추가하기

배경:
 - List View를 보여주는 Fragment로 전환

RecyclerView 위젯은 ListView의 업그레이드 버전으로 데이터 양이 많은 경우 스크롤을 효율적으로 수행할 수 있는 위젯이다.

refer: http://developer.android.com/intl/ko/training/material/lists-cards.html

위 그림과 같이 Adapter를 통해 데이터에 접근하며, 
LayoutManager를 통해 위젯 내부 항목들을 배치한다.

따라서 RecyclerView를 적용하기 위해서는
    - LayoutManager
    - Adaper
를 지정해주어야 한다.



1. 리스트에 보여질 각 항목 item layout 생성
다음과 같이 "id contents" 로 구성하였다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />
    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>
cs



2. 리스트 layout 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
 <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/collection_list"
    android:name="com.tong.android.fragment.CollectionListFragment"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:background="#ECEFF1"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.tong.android.fragment.CollectionListFragment"
    tools:listitem="@layout/fragment_item" />
cs




3. Adapter 선언
RecyclerView.Adapter를 상속받아 작성하였다는 점과
내부에 ReCyclerView.ViewHolder를 확장한 ViewHolder Class를 선언하였다는 것이 확인 포인트이다.
ViewHolder가 RecyclerView에 보여질 각 항목 아이템들을 담는 그릇이라고 보면 될 것 같다.
그리고 onBindViewHolder가 호출되어 ViewHolder에 실제 데이터를 입히게 된다.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class MyListAdapter extends RecyclerView.Adapter< MyListAdapter.ViewHolder> {
    private List<My> myList;
    public MyListAdapter(List<My> myList) {
        this.myList = myList;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_item, parent, false);
        return new ViewHolder(v);
    }
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        My my = myList.get(position);
        holder.mIdView.setText(String.valueOf(position + 1));
        holder.mContent.setText(my.toString());
    }
    @Override
    public int getItemCount() {
        return myList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContent;
        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContent = (TextView) view.findViewById(R.id.content);
        }
    }
}
cs



4. Fragment에 LayoutManager와 Adapter 지정
위에서 작성한 Adapter를 Fragment의 RecyclerView에 지정해주고,
LayoutManager는 기본적으로 사용되는 LinearLayoutManager를 사용할 수 있다.


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
31
32
33
34
35
36
public class MyListFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    public MyListFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView mRecyclerView = (RecyclerView) view;
            mRecyclerView.setHasFixedSize(true);
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(context);
            mRecyclerView.setLayoutManager(mLayoutManager);
            // specify an adapter (see also next example)
            mAdapter = new CollectionListAdapter(myList);
            mRecyclerView.setAdapter(mAdapter);
        }
        
        return view;
     }
}
cs



reference:
 - http://developer.android.com/intl/ko/training/material/lists-cards.html

댓글

이 블로그의 인기 게시물

[Android] Fragment 위에 Dialog 띄우기

배경:  - Fragment에 Google Maps를 올려 사용자에게 보여주고 있다.  - 사용자가 Dialog 창을 열어 검색을 할 수 있게 하고 싶다. 1. Dialog layout xml 생성 Dialog 창에는 하나의 EditText를 추가하여 사용자로 하여금 String을 입력받게 한다. 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 31 32 < LinearLayout   xmlns:android = "http://schemas.android.com/apk/res/android"         android:orientation = "vertical"         android:layout_width = "wrap_content"         android:layout_height = "wrap_content" >     < LinearLayout                 android:orientation = "horizontal"                 android:layout_width = "match_parent"                 android:layout_height = "wrap_content" >         < TextView                         android:layout_width = "match_parent"                         android:layout_height = "match_parent&quo

미니 메추리 키우기 - 사육장 만들기

미니 메추리는 우리가 알고 있는 일반 메추리보다 조금 작은 개체입니다. 버튼퀼(버튼퀘일)이라고도 불리죠. 일반 메추리보다 작기도 하고 짝이 맞는 암수가 같이 있으면 그리 시끄럽지도 않습니다. 여러 모로 키우기가 좀더 수월하죠. 첫 번째 단계로 먼저 아이들이 지낼 집을 만들어 주었습니다. 사실 여러 고민을 많이 했어요 지금 소개하는 집을 만들기 전에는 120L 짜리 대형 리빙 박스로 집을 만들어 주었었죠. 값이 저렴하고 개량하는 것이 크게 어렵지 않기 때문에 많은 분들이 리빙 박스를 개조하여 집을 만들어 주고 있어요. 저 같은 경우는 보온을 생각해서 안쪽에는 단열재를 덧대기도 했죠. 하지만 사실 리빙 박스로 집을 만드는게 아주 쉽지만은 않아요. 물론 있는 그대로를 사용하신다면 어려울 건 전혀 없죠. 그런데 만약 전구를 달기 위해 구멍을 뚫거나, 환기 구멍을 뚫거나 기타 여러 필요에 의해 리빙 박스를 뜯어 고쳐야 한다면 이야기가 달라지죠. 저도 사실 이런 불편함에 고민고민을 하다가 오늘 소개해 드릴 두 번째 집과 같은 것을 생각하게 되었어요. 바로 시중에서 쉽게 구할 수 있는 종이 박스를 활용한 것인데요. 위쪽 뚜껑에는 구멍을 두 개를 뚫었어요. 작은 구멍은 온도 조절을 위한 전구 바로 위쪽으로 온도가 너무 올라갈 경우 온도 조절을 위해 뚫어 놓았고요.  아래 좀더 큰 구멍은 물, 먹이 등을 교체해주기 위한 구멍이에요.  정면에는 창을 내어 관찰할 수 있게 했어요. 지금은 저 가운데도 잘라내서 크게 창 하나로 만들었어요. 안쪽에는 온도계를 비치하여 내부 온도를 확인할 수 있게 해두었습니다. (지금 생각해보니 전구 바로 아래쪽에 위치한 탓에 제대로 된 온도 측정이 될지 모르겠네요;;;) 그리고 보셔서 아시겠지만, 내부 바닥, 옆면에 단