본문 바로가기
IT/Android

Android Retrofit2 데이터 RecyclerView 적용하기

by TechTonic 2022. 9. 29.
반응형

Retrofit2 데이터 RecyclerView 사용 개요

지난 발행글에서 Retrofit2를 사용하여 공공데이터포탈의 API를 사용하여 데이터 가져오기를 해보았습니다.

이번글에서는 해당 데이터를 기반으로 RecyclerView를 활용하여 리스트뷰를 만드는 작업을 해보겠습니다.

 

RecyclerView 리스트 화면 구현

간단한 제목과 내용만 Text로 나타내는 리스트를 만들 것입니다.

아래는 RecyclerView를 그릴 activity_main layout입니다.

 

activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    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="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

별 다른 내용은 없습니다. 앱 메인화면 전체에 리스트 내용을 출력합니다.

아래는 RecyclerView에 들어갈 각각 Item View 화면 구성 내용입니다.

 

service_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="@color/purple_200"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp">

        <TextView
            android:id="@+id/serviceName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:gravity="center"
            android:text="Name"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/servicePurpose"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:gravity="center_vertical"
            android:text="Name"
            android:textSize="12sp" />


    </LinearLayout>


</LinearLayout>

아래 샘플 이미지와 같이 제목, 내용 두 가지 Text를 뿌려줄 것입니다.

리스트 내용

RecyclerView Adapter 만들기

우선 화면을 그릴 Adapter를 생성해 줍니다.

 

ServiceAdapter.java

public class ServiceAdapter extends RecyclerView.Adapter<ServiceAdapter.ViewHolder>{

    private List<ServiceModel> items;

    public ServiceAdapter(List<ServiceModel> items){
        this.items = items;
    }

    @NonNull
    @Override
    public ServiceAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.service_list_item , parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ServiceModel item = items.get(position);
        holder.setItem(item);
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private TextView rank, serviceName, servicePurpose;

        public ViewHolder(View itemView) {
            super(itemView);
            serviceName = itemView.findViewById(R.id.serviceName);
            servicePurpose = itemView.findViewById(R.id.servicePurpose);
        }

        public void setItem(ServiceModel item){

            serviceName.setText(item.getServiceName());
            servicePurpose.setText(item.getServicePurpose());
        }
    }

}

ViewHolder 안의 layout 은 위에서 생성한 item view의 layout로 잡아줘야 하고, List에서 사용하는 model 은 각자 생성한 List로 모두 변경해 주면 됩니다.

 

RecyclerView 실행하기

위 모든 구현이 완료되었다면, 이제 출력할 화면에서 RecyclerView 관련 내용을 추가 호출 해주면 됩니다.

 

 MainActivity.java (onCreate)

public class MainActivity extends AppCompatActivity {

    ...
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;


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

        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
		
        ...
        
        mAdapter = new ServiceAdapter(arr);
        recyclerView.setAdapter(mAdapter);
        
	}

내용은 간단합니다. 

  • 전역 변수로 Adapter 및 recyclerview를 선언
  • LinearLayoutManager를 recyclerview에 세팅
  • recyclerview에 보일 List를 Adapter에 초기화

이렇게 RecyclerView를 통해 리스트를 생성하는 방법을 알아보았습니다.

 

다음으로 RecyclerView 리스트 Click event에 대해서는 아래 링크를 참고하길 바란다.

2022.09.29 - [IT/Android] - Android RecyclerView Click Event 적용하기 (클릭 이벤트)

 

Android RecyclerView Click Event 적용하기 (클릭 이벤트)

개요 이전 발행글에서 RecyclerView 를 적용하는 방법에 대해 알아보았다. RecyclerView 적용 방법에 대한 내용은 아래 링크를 참조하길 바란다. 2022.09.29 - [IT/Android] - Android Retrofit2 데이터 RecyclerV..

soir1984.tistory.com

 

 

 

반응형

댓글