안드로이드

안드로이드 RecyclerView Header 추가하기 ( feat. DataBinding )

알통몬_ 2017. 12. 1. 15:11
반응형


공감 및 댓글은 포스팅 하는데

 아주아주 큰 힘이 됩니다!!

포스팅 내용이 찾아주신 분들께 

도움이 되길 바라며

더 깔끔하고 좋은 포스팅을 

만들어 나가겠습니다^^

 


안드로이드 RecyclerView 에 Header 를 추가하는 방법에 대해 알아보겠습니다.


헤더는 어떤 용도로 쓰이냐 하면


예를 들면 카카오톡 친구목록에 보면

'내프로필' 아래에 내프로필이 보이고


'즐겨찾기' 아래애 즐겨찾기한 친구목록이 보이고 하죠??


그런 용도로 많이 사용합니다.


이번 포스팅에서는 그 Header 를 DataBinding을 같이 사용해서 추가해 보겠습니다.


먼저 RecyclerView 에 들어갈 item 에 Header 로 사용될 header_item 이 별도로 필요합니다.


저는 그저께 시작한 알통몬톡에 사용한 것들로 준비했습니다.


item_profile.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version="1.0" encoding="utf-8"?>
<layout 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.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:contentDescription="@string/app_name"
            android:id="@+id/profileImgView"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:padding="8dp"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_people_black_24dp"
            app:layout_constraintEnd_toStartOf="@+id/userNameTv"/>
        <TextView
            app:layout_constraintStart_toEndOf="@+id/profileImgView"
            app:layout_constraintEnd_toStartOf="@+id/profileMsgTv"
            android:paddingStart="16dp"
            android:paddingEnd="0dp"
            android:id="@+id/userNameTv"
            android:layout_width="wrap_content"
            android:layout_height="64dp"
            android:gravity="center|start"
            android:textColor="@color/black"
            android:textSize="24sp"
            tools:text="name" />
        <TextView
            android:id="@+id/profileMsgTv"
            android:layout_width="match_parent"
            android:gravity="center|end"
            android:paddingStart="0dp"
            android:paddingEnd="16dp"
            android:layout_height="64dp"
            app:layout_constraintStart_toEndOf="@+id/userNameTv"
            app:layout_constraintEnd_toEndOf="parent"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/userNameTv" />
    </android.support.constraint.ConstraintLayout>
</layout>
cs


item_header.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="utf-8"?>
<layout 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.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <TextView
            android:id="@+id/friendHeaderTv"
            android:layout_width="match_parent"
            android:layout_height="24dp"
            android:gravity="center|start"
            android:paddingEnd="0dp"
            android:paddingStart="16dp"
            android:textColor="@color/black"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            tools:text="name" />
 
        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/friendHeaderTv" />
    </android.support.constraint.ConstraintLayout>
</layout>
cs


[ 광고 보고 가시죠! ]



[ 감사합니다! ]


Item들을 담을 Profile.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Profile {
 
    private int url;
    private String name;
    private String msg;
 
    public Profile(int url, String name, String msg) {
        this.url = url;
        this.name = name;
        this.msg = msg;
    }
 
    public int getUrl() {
        return url;
    }
 
    public String getName() {
        return name;
    }
 
    public String getMsg() {
        return msg;
    }
}
 
cs



그리고 RecyclerView.ViewHolder를 상속받은 어댑터가 필요하구요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package altong.mon.amtalk;
 
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
 
import java.util.Vector;
 
import altong.mon.amtalk.databinding.ItemHeaderBinding;
import altong.mon.amtalk.databinding.ItemProfileBinding;
 
/*
 * Created by 15U560 on 2017-11-29.
 */
 
public class ProfileAdapter extends RecyclerView.Adapter {
 
    private static final int MY_HEADER = 0;
 
    private static final int MY_PROFILE = 1;
 
    private static final int FRIEND_HEADER = 2;
 
    private Vector<Profile> profiles;
 
    private Context context;
 
    public ProfileAdapter(Vector<Profile> profiles, Context context) {
        this.profiles = profiles;
        this.context = context;
    }
 
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
 
        if( viewType == MY_HEADER || viewType == FRIEND_HEADER ) {
            ItemHeaderBinding headerBinding = ItemHeaderBinding.inflate(LayoutInflater.from(context), parent, false);
            holder = new HeaderHolder(headerBinding);
        } else {
            ItemProfileBinding profileBinding = ItemProfileBinding.inflate(LayoutInflater.from(context), parent, false);
            holder = new ProfileHolder(profileBinding);
        }
        return holder;
    }
 
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(position == MY_HEADER && holder instanceof HeaderHolder) {
            HeaderHolder itemViewHolder = (HeaderHolder) holder;
            final ItemHeaderBinding binding = itemViewHolder.binding;
            binding.friendHeaderTv.setText(profiles.get(position).getName());
        } else if (position == FRIEND_HEADER && holder instanceof HeaderHolder) {
            HeaderHolder itemViewHolder = (HeaderHolder) holder;
            final ItemHeaderBinding binding = itemViewHolder.binding;
            binding.friendHeaderTv.setText(profiles.get(position).getName());
        } else if (position == MY_PROFILE && holder instanceof ProfileHolder) {
            ProfileHolder itemViewHolder = (ProfileHolder) holder;
            final ItemProfileBinding binding = itemViewHolder.binding;
            binding.userNameTv.setText(profiles.get(position).getName());
            binding.profileMsgTv.setText(profiles.get(position).getMsg());
            binding.profileImgView.setImageResource(profiles.get(position).getUrl());
        } else {
            ProfileHolder itemViewHolder = (ProfileHolder) holder;
            final ItemProfileBinding binding = itemViewHolder.binding;
            binding.userNameTv.setText(profiles.get(position).getName());
            binding.profileMsgTv.setText(profiles.get(position).getMsg());
            binding.profileImgView.setImageResource(profiles.get(position).getUrl());
        }
    }
 
    /*
     * item position 에 따른 타입을 확인하는데 필요합니다.
    */   
    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return MY_HEADER;
        } else if (position == 2) {
            return FRIEND_HEADER;
        } else {
            return position;
        }
    }
 
    // 보통 ArrayList<Type> 에 아이템들이 담겨서 넘어오죠. 저는 Vector를 주로 사용하는데요.
    // Header_item 에 들어가는 내용을 완전히 분리하고 싶으시면 profiles.size() + 1;
    // 사이즈를 하나 더 해주시면 됩니다.
    // 저는 그냥 벡터에 들어오는 객체에 해더를 같이 넣어서 그냥 size()로 아이템 카운트를 하게 했습니다.
    @Override
    public int getItemCount() {
        return profiles.size();
    }
 
 
    
    // HeaderItem Binding에 사용되는 Holder
    private class HeaderHolder extends RecyclerView.ViewHolder {
 
        ItemHeaderBinding binding;
 
        HeaderHolder(ItemHeaderBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
    
    // ProfileItem Binding 사용되는 Holder
    private class ProfileHolder extends RecyclerView.ViewHolder {
 
        ItemProfileBinding binding;
 
        ProfileHolder(ItemProfileBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
 
    }
}
 
cs



[ 광고 보고 가시죠! ]



[ 감사합니다! ]

마지막으로 저는 Activity가 아닌 Fragment에 RecylerView를 사용했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class FriendListFragment extends Fragment {
 
    FragmentFriendlistBinding binding;
    Vector<Profile> profiles;
 
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                inflater, R.layout.fragment_friendlist, container, false);
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        binding.myListView.setLayoutManager(manager);
        profiles = new Vector<>();
        profiles.add(new Profile(0,"내 프로필","")); // Header
        profiles.add(new Profile(R.drawable.naltong,"알통몬","촤하하"));
        profiles.add(new Profile(0,"친구목록","")); // Header
        profiles.add(new Profile(R.drawable.ngenyuk,"근육몬","추후후"));
        profiles.add(new Profile(R.drawable.nguiruk,"괴력몬","췌헤헤"));
        binding.myListView.setAdapter(new ProfileAdapter(profiles, getContext()));
        View view = binding.getRoot();
 
        //here data must be an instance of the class MarsDataProvider
        return view;
    }
}
 
cs


제공해드린 소스들을 가지고 테스트 해보시면, 크게 에러가나거나 어렵진 않으실 거에요. 실행화면입니다. 



이상입니다.

감사합니다.


반응형