메뉴 건너뛰기

조회 수 931 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

RecyclerView는 Adapter가 관리하는 Data Set의 특정 데이터 항목에 대하여 미리 정의된 View를 통해 스크롤이 있는 List 형식으로 표현할 수 있습니다. 이번 포스팅에서는 한 개의 RecyclerView에서 여러 Type의 View를 정의해놓고 데이터의 타입에 따라 각각 다른 ViewType을 적용시키는 방법을 알아보겠습니다.

 

 

 

간단한 채팅 UI를 가지는 RecyclerView를 구현 할것입니다. 해당 RecyclerView에서 사용하는 ViewType은 3개로 중앙에 표시되는 Type과 왼쪽에 채팅내용이 나오는 Type과 오른쪽에 채팅 내용이 나오는 Type 3개로 구성됩니다.


1. DataItem

public class DataItem {

    private String content;
    private String name;
    private int viewType;

    public DataItem(String content, String name ,int viewType) {
        this.content = content;
        this.viewType = viewType;
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public String getName() {
        return name;
    }

    public int getViewType() {
        return viewType;
    }
}

2. ViewType에 대한 CodeValue 정의

public class Code {
    public class ViewType{
        public static final int LEFT_CONTENT = 0;
        public static final int RIGHT_CONTENT = 1;
        public static final int CENTER_CONTENT = 2;
    }
}

3. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>

4. 각 ViewType에 대한 View 정의

■ center_content.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content">

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        android:textSize="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

▼ 채팅 UI에서 Center의 Content를 표시하기 위한 View입니다. ViewType은 CENTER_CONTENT Code 값을 가지게 됩니다.

 

■ left_content.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintLeft_toRightOf="@id/imageView"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:text="TextView"
        app:layout_constraintLeft_toRightOf="@id/imageView"
        app:layout_constraintTop_toBottomOf="@id/name" />
</android.support.constraint.ConstraintLayout>

■ right_content.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintRight_toLeftOf="@id/imageView"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="TextView"
        app:layout_constraintRight_toLeftOf="@id/imageView"
        app:layout_constraintTop_toBottomOf="@id/name" />
</android.support.constraint.ConstraintLayout>

5. Adapter 구현

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

        private ArrayList<DataItem> myDataList = null;

        MyAdapter(ArrayList<DataItem> dataList)
        {
            myDataList = dataList;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View view;
            Context context = parent.getContext();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(viewType == Code.ViewType.CENTER_CONTENT)
            {
                view = inflater.inflate(R.layout.center_content, parent, false);
                return new CenterViewHolder(view);
            }
            else if(viewType == Code.ViewType.LEFT_CONTENT)
            {
                view = inflater.inflate(R.layout.left_content, parent, false);
                return new LeftViewHolder(view);
            }
            else
            {
                view = inflater.inflate(R.layout.right_content, parent, false);
                return new RightViewHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
        {
            if(viewHolder instanceof CenterViewHolder)
            {
                ((CenterViewHolder) viewHolder).content.setText(myDataList.get(position).getContent());
            }
            else if(viewHolder instanceof LeftViewHolder)
            {
                ((LeftViewHolder) viewHolder).name.setText(myDataList.get(position).getName());
                ((LeftViewHolder) viewHolder).content.setText(myDataList.get(position).getContent());
            }
            else
            {
                ((RightViewHolder) viewHolder).name.setText(myDataList.get(position).getName());
                ((RightViewHolder) viewHolder).content.setText(myDataList.get(position).getContent());
            }
        }

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

        @Override
        public int getItemViewType(int position) {
            return myDataList.get(position).getViewType();
        }

        public class CenterViewHolder extends RecyclerView.ViewHolder{
            TextView content;

            CenterViewHolder(View itemView)
            {
                super(itemView);

                content = itemView.findViewById(R.id.content);
            }
        }

        public class LeftViewHolder extends RecyclerView.ViewHolder{
            TextView content;
            TextView name;
            ImageView image;

            LeftViewHolder(View itemView)
            {
                super(itemView);

                content = itemView.findViewById(R.id.content);
                name = itemView.findViewById(R.id.name);
                image = itemView.findViewById(R.id.imageView);
            }
        }

        public class RightViewHolder extends RecyclerView.ViewHolder{
            TextView content;
            TextView name;
            ImageView image;

            RightViewHolder(View itemView)
            {
                super(itemView);

                content = itemView.findViewById(R.id.content);
                name = itemView.findViewById(R.id.name);
                image = itemView.findViewById(R.id.imageView);
            }
        }
 

▼ 가장 중요한 Adapter 구현 내용입니다. ViewType 마다 ViewHolder 클래스를 따로 정의하며 onCreateViewHolder() 함수에서 두 번째 인자로 넘어오는 viewType 값에 따라 다른 ViewHolder 객체를 생성하여 리턴하게 됩니다. 두 번째 인자로 넘어오는 viewType은 getItemViewType() 함수를 재정의하여 각 아이템 항목에 맞는 ViewType 값을 리턴하도록 재정의합니다.

6. MainActivity.java 구현

public class MainActivity extends AppCompatActivity {

    private ArrayList<DataItem> dataList;

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

        this.initializeData();

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

        LinearLayoutManager manager
                = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false);

        recyclerView.setLayoutManager(manager); // LayoutManager 등록
        recyclerView.setAdapter(new MyAdapter(dataList));  // Adapter 등록
    }

    public void initializeData()
    {
        dataList = new ArrayList<>();

        dataList.add(new DataItem("사용자1님이 입장하셨습니다.", null,  Code.ViewType.CENTER_CONTENT));
        dataList.add(new DataItem("사용자2님이 입장하셨습니다.", null,  Code.ViewType.CENTER_CONTENT));
        dataList.add(new DataItem("안녕하세요", "사용자1",  Code.ViewType.LEFT_CONTENT));
        dataList.add(new DataItem("안녕하세요", "사용자2",  Code.ViewType.RIGHT_CONTENT));

    }
}

List of Articles
번호 제목 날짜 조회 수
257 화면 회전에 따른 애니메이션 효과 구현하기 2015.07.16 8055
256 화면 해상도에 관계없는 레이아웃(Layout) 만들기 file 2015.07.16 8641
255 화면 전환해도 데이터 유지 예제 2015.07.26 9204
254 하이브리드앱 기본 - WebView로 웹페이지 띄우기 file 2020.12.14 1025
253 하이브리드 앱에서의 세션관리(로그인 상태 유지) 2018.12.27 4998
252 푸시 서비스(GCM)에 대해 알아보자 file 2015.07.01 7000
251 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (3) file 2015.07.16 6267
250 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (2) file 2015.07.16 7292
249 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (1) file 2015.07.16 6726
248 폰갭(PhoneGap) 플러그인 사용하기 2015.06.29 7356
247 폰갭(PhoneGap) 플러그인 만들기 2015.06.29 8413
246 폰갭(PhoneGap) 에서 페이지들간의 이동 2015.06.29 8455
245 폰갭(PhoneGap) & jQuery Mobile 로 안드로이드 어플 개발 file 2015.06.29 7839
244 폰갭 비콘 디텍팅 안될 때 (기본적인건 다 되있어야됨) 2015.07.26 6529
243 패키지명을 한꺼번에 변경하기 (Refactor) file 2020.12.14 295
242 특정 폴더에서 오래된 파일 삭제하기 2015.07.16 6767
241 트리뷰(TreeView) 컨트롤 file 2014.10.16 6720
240 탭 뷰에 탭 추가하기, 아이콘 넣기 file 2015.07.16 9360
239 클래스나눠서 xml 파싱과 FTP를이용하여 안드로이드에서 활용하기 2014.08.28 6180
238 카카오톡 분석하기 (2) - 카카오톡 암호화 함수 찾기 file 2016.05.26 9599
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved