Today Yewon Learned

[Android Studio] RecyclerView 구현하기 본문

Android Sudio

[Android Studio] RecyclerView 구현하기

데브워니 2022. 6. 15. 14:43

RecyclerView 란?

RecyclerView란 이미지나 텍스트를 리스트화해서 스크롤하며 볼 수 있게 해주는 컨테이너다.

- 기존에 사용하던 ListView 와 비슷하지만, 정확히는 ListView 의 확장판 개념이며, 대부분 RecyclerView로 대체된 상태

- RecyclerView는 ListView보다 향상된 성능 제공

- Adapter의 ViewHolder를 이용

* ViewHolder를 사용하는 이유는?  맨 처음 화면에 보이는 뷰 객체를 홀딩(기억)하고 있어야 함

 

build.gradle (:app)

dependencies {
	implementation "androidx.recyclerview:recyclerview:1.2.1"
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

  </androidx.constraintlayout.widget.ConstraintLayout>

 

activity_recycler_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp">

    <ImageView
        android:id="@+id/imgView_item"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txt_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/imgView_item" />

    <TextView
        android:id="@+id/txt_sub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/txt_main" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivitiy.java

package com.example.schedule;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private ArrayList<RecyclerViewItem> mList;
    private RecyclerViewAdapter mRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firstInit();

        for(int i=0;i<5;i++){
            //addItem("iconName", "MAC" + i, "loaction");
            addItem("iconName", "MAC" + i, "loaction");
        }

        mRecyclerViewAdapter = new RecyclerViewAdapter(mList);
        mRecyclerView.setAdapter(mRecyclerViewAdapter);
        //mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 세로
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)); //가로
    }

    public void firstInit(){
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mList = new ArrayList<>();
    }

    public void addItem(String imgName, String mainText, String subText){
        RecyclerViewItem item = new RecyclerViewItem();

        item.setImgName(imgName);
        item.setMainText(mainText);
        item.setSubText(subText);

        mList.add(item);
    }
}

 

RecyclerViewAdapter.java

package com.example.schedule;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imgView_item;
        TextView txt_main;
        TextView txt_sub;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            imgView_item = (ImageView) itemView.findViewById(R.id.imgView_item);
            txt_main = (TextView) itemView.findViewById(R.id.txt_main);
            txt_sub = (TextView) itemView.findViewById(R.id.txt_sub);
        }
    }

    private ArrayList<RecyclerViewItem> mList = null;

    public RecyclerViewAdapter(ArrayList<RecyclerViewItem> mList) {
        this.mList = mList;
    }

    // 아이템 뷰를 위한 뷰홀더 객체를 생성하여 리턴
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.activity_recycler_item, parent, false);
        RecyclerViewAdapter.ViewHolder vh = new RecyclerViewAdapter.ViewHolder(view);
        return vh;
    }

    // position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시
    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        RecyclerViewItem item = mList.get(position);

        holder.imgView_item.setImageResource(R.drawable.ic_launcher_background);   // 사진 없어서 기본 파일로 이미지 띄움
        holder.txt_main.setText(item.getMainText());
        holder.txt_sub.setText(item.getSubText());
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
}

 

RecyclerViewItem.java

package com.example.schedule;

public class RecyclerViewItem {
    private String mImagName;
    private String mMainText;
    private String mSubText;
    
    public void setImgName(String imgName) {
        this.mImagName = imgName;
    }

    public void setMainText(String mainText) {
        this.mMainText = mainText;
    }

    public void setSubText(String subText) {
        this.mSubText = subText;
    }

    public String getMainText() {
        return mMainText;
    }

    public String getSubText() {
        return mSubText;
    }
}

 

[실행 화면]

 

 

 

[참고]

 

RecyclerView로 동적 목록 만들기  |  Android 개발자  |  Android Developers

RecyclerView로 동적 목록 만들기   Android Jetpack의 구성요소 RecyclerView를 사용하면 대량의 데이터 세트를 효율적으로 표시할 수 있습니다. 개발자가 데이터를 제공하고 각 항목의 모양을 정의하면 R

developer.android.com

 

 

GitHub - android/views-widgets-samples: Multiple samples showing the best practices in views-widgets on Android.

Multiple samples showing the best practices in views-widgets on Android. - GitHub - android/views-widgets-samples: Multiple samples showing the best practices in views-widgets on Android.

github.com

 

 

[안드로이드] RecyclerView를 커스텀해서 가로,세로 구현하기

ListView에 이어서 RecyclerView를 만들어보자 이제부터는 프로젝트 만드는건 생략함. 물론 이론 설명도 생략. - ListView는 세로로 리스트가 나타나지만 RecyclerView는 가로로 리스트를 나타낼 수도 있다!

taek2.tistory.com

 

Comments