본문 바로가기
안드로이드 자바

[Java][Android] 확장형 리사이클러뷰 만들기

by teamnova 2023. 8. 14.

안녕하세요. 오늘은 안드로이를 이용해서 확장형 리사이클러뷰를 만들어보도록하겠습니다. 

 

먼저, 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="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

고정으로 보이는 목록의 list_head.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="match_parent"
    android:layout_height="70dp"
    android:background="#BE7ACA">

    <TextView
        android:id="@+id/header_title_tv"
        android:textColor="#191B1E"
        android:textSize="18sp"
        android:gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <ImageView
        android:id="@+id/expand_btn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginTop="20dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/ic_launcher_foreground"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 헤더 목록을 클릭하면 확장되는 자식 목록을 위한 list_child 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="70dp"
    android:background="#E5EF82">

    <ImageView
        android:id="@+id/child_iv"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/child_title_tv"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginStart="20dp"
        android:gravity="center_vertical"
        android:textColor="#837D7D"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/child_iv"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toEndOf="@+id/child_iv"
        app:layout_constraintTop_toTopOf="@+id/child_iv" />

</androidx.constraintlayout.widget.ConstraintLayout>

xml 작업이 다 종료되시면,  java class를 하나 생성하고, 생성자를 선언해줍니다.

import java.util.List;
    public class FriendItem {
        public int type;
        public String text;
        public String username;
        public String msg;
        public String profile;
        public List<FriendItem> invisibleChildren;

        public FriendItem(int type, String text, String username, String profile) {
            this.type = type;
            this.text = text;
            this.username = username;
            this.profile = profile;
        }
    }

 

어뎁터를 추가해주세요. expandablelistadpater.java

package com.example.exapndalblerecyclerviewtest;
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.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public static final int HEADER = 0;
    public static final int CHILD = 1;

    private List<FriendItem> data;

    public ExpandableListAdapter(List<FriendItem> data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
        View view = null;
        Context context = parent.getContext();
        switch (type) {
            case HEADER:
                LayoutInflater inflaterHeader = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflaterHeader.inflate(R.layout.list_header, parent, false);
                ListHeaderViewHolder header = new ListHeaderViewHolder(view);
                return header;
            case CHILD:
                LayoutInflater inflaterChild = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflaterChild.inflate(R.layout.list_child, parent, false);
                ListChildViewHolder child = new ListChildViewHolder(view);
                return child;

        }
        return null;
    }

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final FriendItem item = data.get(position);
        switch (item.type) {
            case HEADER:
                final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
                itemController.refferalItem = item;
                itemController.header_title.setText(item.text);
                if (item.invisibleChildren == null) {
                    itemController.btn_expand_toggle.setImageResource(R.drawable.ic_launcher_foreground);
                } else {
                    itemController.btn_expand_toggle.setImageResource(R.drawable.ic_launcher_foreground);
                }
                itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.invisibleChildren == null) {
                            item.invisibleChildren = new ArrayList<FriendItem>();
                            int count = 0;
                            int pos = data.indexOf(itemController.refferalItem);
                            while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
                                item.invisibleChildren.add(data.remove(pos + 1));
                                count++;
                            }
                            notifyItemRangeRemoved(pos + 1, count);
                            itemController.btn_expand_toggle.setImageResource(R.drawable.ic_launcher_foreground);
                        } else {
                            int pos = data.indexOf(itemController.refferalItem);
                            int index = pos + 1;
                            for (FriendItem i : item.invisibleChildren) {
                                data.add(index, i);
                                index++;
                            }
                            notifyItemRangeInserted(pos + 1, index - pos - 1);
                            itemController.btn_expand_toggle.setImageResource(R.drawable.ic_launcher_foreground);
                            item.invisibleChildren = null;
                        }
                    }
                });
                break;
            case CHILD:
                final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
                itemController1.refferalItem = item;
                itemController1.child_title.setText(item.username);

                break;
        }
    }

    @Override
    public int getItemViewType(int position) {
        return data.get(position).type;
    }


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

    private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
        public TextView header_title;
        public ImageView btn_expand_toggle;
        public FriendItem refferalItem;

        public ListHeaderViewHolder(View itemView) {
            super(itemView);
            header_title = (TextView) itemView.findViewById(R.id.header_title_tv);
            btn_expand_toggle = (ImageView) itemView.findViewById(R.id.expand_btn);
        }
    }
    private static class ListChildViewHolder extends RecyclerView.ViewHolder {
        public TextView child_title,child_msg;
        public FriendItem refferalItem;
        public ImageView child_img;

        public ListChildViewHolder(View itemView) {
            super(itemView);
            child_title = itemView.findViewById(R.id.child_title_tv);
            child_img = itemView.findViewById(R.id.child_iv);
        }
    }




}

main.java

package com.example.exapndalblerecyclerviewtest;

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

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerview;

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


        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        List<FriendItem> data = new ArrayList<>();  // 데이터를 담을 List

        data.add(new FriendItem(ExpandableListAdapter.HEADER, "추천친구",null,null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "김철수",null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "김영희",null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "김민수",null));


        data.add(new FriendItem(ExpandableListAdapter.HEADER, "내친구",null,null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "형",null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "김사무엘",null));
        data.add(new FriendItem(ExpandableListAdapter.CHILD,null, "강동훈",null));



        recyclerview.setAdapter(new ExpandableListAdapter(data));
    }
}

 

실행결과입니다.