보통인의 오늘 공부/Android

RecyclerView 기본 사용

지롱드보통 2016. 12. 27. 15:07

ListView와 같이 데용량의 데이터를 한정된 화면에 보여주기 위한 클래스이다.

- LayoutManager를 사용하여 ChildView를 더욱 자유롭게 배치할 수 있음

- Adapter를 통해 RecyclerView에 데이터를 공급하고 View를 가공

- ChildView를 생성하고 내용을 구성하는 기능을 ViewHolder를 통해 구현




1. 모듈의 dependencies에 recyclerview-v7를 추가

File > Project Structure 선택 후 팝업의 좌측 Modules에서 사용할 모듈 선택

우측에서 Dependencies 탭을 선택한 후 +버튼을 클릭하고 com.android.support:recyclerview를 검색하여 추가

혹은, 모듈의 gradle 파일에 직접 입력해도 됨

dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     compile 'com.android.support:appcompat-v7:24.2.1'     compile 'com.android.support:recyclerview-v7:24.2.1' }


2. Layout에 RecyclerView 배치

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_recycler_view"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:orientation="vertical"

    tools:context="com.jiyoung.andstudy.activity.RecyclerViewActivity">

....

    <android.support.v7.widget.RecyclerView

        android:id="@+id/recycler_view"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

....

</LinearLayout>


3. ChildView의 Layout 만들기

CardView를 이용해서 이쁘게 만들어 봄 ㅎㅎ (com.android.support:cardview-v7 라이브러리 추가)

CardView는 모서리를 둥글게 하는 속성 (cardCornerRadius), 그림자 속성 (cardElevation) 등을 기능을 지원한다.

<android.support.v7.widget.CardView

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:card_view="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_margin="10dp"

    card_view:cardCornerRadius="12dp"

    card_view:cardElevation="5dp"

    card_view:contentPadding="10dp">


    <RelativeLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content">


        <ImageView

            android:id="@+id/img_thumb"

            android:layout_width="130dp"

            android:layout_height="130dp"

            android:layout_marginRight="5dp"

            android:src="@drawable/sample_0"

            android:scaleType="centerCrop"/>


        <TextView

            android:id="@+id/tv_title"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_toRightOf="@id/img_thumb"

            android:layout_marginBottom="5dp"

            android:lines="1"

            android:ellipsize="end"

            android:textSize="18dp"

            android:text="Title"

            />


        <TextView

            android:id="@+id/tv_desc"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_toRightOf="@id/img_thumb"

            android:layout_below="@id/tv_title"

            android:textSize="13dp"

            android:text="description"/>

    </RelativeLayout>


</android.support.v7.widget.CardView>


4. ViewHolder 구현

위의 ChildView를 생성하고, 데이터를 설정할 ViewHolder를 생성한다.

public class CardViewHolder extends RecyclerView.ViewHolder {


    ImageView imgThumb;

    TextView tvTitle;

    TextView tvDesc;


    ChapterInfo chapterInfo;


    public CardViewHolder(View itemView) {

        super(itemView);


        imgThumb = (ImageView) itemView.findViewById(R.id.img_thumb);

        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);

        tvDesc = (TextView) itemView.findViewById(R.id.tv_desc);

    }


    public void setChapterInfo(ChapterInfo chapterInfo) {

        this.chapterInfo = chapterInfo;


        imgThumb.setImageDrawable(chapterInfo.getImage());

        tvTitle.setText(chapterInfo.getTitle());

        tvDesc.setText(chapterInfo.getDescription());

    }

}

5. Adapter 구현

데이터를 받아 ViewHolder를 생성하는 Adapter를 구현

public class RecyclerChapterAdapter extends RecyclerView.Adapter<CardViewHolder> {


    List<ChapterInfo> items = new ArrayList<ChapterInfo>();

    Context mContext;


    public RecyclerChapterAdapter(Context context) {

        this.mContext = context;

        items.add(new ChapterInfo(context.getResources().getDrawable(R.drawable.sample_0), "TEST0", "this is test1. this is test1. this is test1. this is test1."));

        items.add(new ChapterInfo(context.getResources().getDrawable(R.drawable.sample_1), "TEST1", "this is test1. this is test1. this is test1. this is test1."));

        items.add(new ChapterInfo(context.getResources().getDrawable(R.drawable.sample_2), "TEST2", "this is test1. this is test1. this is test1. this is test1."));

        items.add(new ChapterInfo(context.getResources().getDrawable(R.drawable.sample_3), "TEST3", "this is test1. this is test1. this is test1. this is test1."));

    }


    @Override

    public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View view = LayoutInflater.from(viewGroup.getContext())

.inflate(R.layout.item_card_view, viewGroup, false);

        return new CardViewHolder(view);

    }


    @Override

    public void onBindViewHolder(CardViewHolder holder, int position) {

        holder.setChapterInfo(items.get(position));

    }


    @Override

    public int getItemCount() {

        return items.size();

    }

}


6. RecyclerView에 Adapter 적용

public class RecyclerViewActivity extends AppCompatActivity {


    RecyclerView recyclerView;

    RecyclerView.LayoutManager layoutManager;

    RecyclerView.Adapter adapter;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recycler_view);


        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);


        adapter = new RecyclerChapterAdapter(this);

        recyclerView.setAdapter(adapter);


    }

}