(Tutorial Android) Add Header in RecyclerView

Tuesday, April 12, 2016

RecyclerView merupakan widget material design yang memiliki kemampuan yang sangat bagus dibandingkan dengan ListView. RecyclerView adalah widget yang lebih fleksibel dan mampu menampung lebih banyak data dan lebih efisien. Selain itu, RecyclerView memiliki method ViewHolder yang memungkinkan kita menambahkan list data dari layout tertentu.

Pada tutorial kali ini, saya ingin membahas bagaimana menambahkan header di RecyclerView. Sebelum kita mulai, alangkah lebih baik membaca postingan saya yang tentang (Tutorial Android) RecyclerView and CardView Android Material Design.

Karena saya menggunakan sampel projectnya yang sama.
Nah, tinggal kita modifikasi sedikit hehe.

Pertama,
Buat layout baru sebagai header.

header.xml


Kemudian kita buat adapter untuk RecyclerView. Nah disini kita modifikasi dengan menambahkan header.

MemberListAdapter.java
package wim.example.com.androidheaderrecyclerview.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import wim.example.com.androidheaderrecyclerview.R;
import wim.example.com.androidheaderrecyclerview.model.Member;

/**
 * Created by wim on 4/12/16.
 */
public class MemberListAdapter extends RecyclerView.Adapter<Recyclerview.ViewHolder> {

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    private List<Member> memberList;



    public MemberListAdapter() {
        memberList = new ArrayList<>();
    }

    private void add(Member item) {
        memberList.add(item);
        notifyItemInserted((memberList.size() + 1)- 1);
    }

    public void addAll(List memberList) {
        for (Member member : memberList) {
            add(member);
        }
    }

    public void remove(Member item) {
        int position = memberList.indexOf(item);
        if (position > -1) {
            memberList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void clear() {
        while (getItemCount() > 1) {
            remove(getItem(-1));
        }
    }

    public Member getItem(int position){
        return memberList.get(position + 1);
    }

    @Override
    public int getItemViewType (int position) {
        if(isPositionHeader (position)) {
            return TYPE_HEADER;
        }
        return TYPE_ITEM;
    }

    public boolean isPositionHeader(int position) {
        return position == 0;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
            return new HeaderViewHolder(view);
        } else if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_member, parent, false);
            return new MemberViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderViewHolder) {
            HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
            headerViewHolder.imgHeader.setImageResource(R.drawable.header);
        } else if (holder instanceof MemberViewHolder) {
            MemberViewHolder memberViewHolder = (MemberViewHolder) holder;
            Member member = memberList.get(position - 1);
            memberViewHolder.memberThumb.setImageResource(member.getThumb());
            memberViewHolder.memberName.setText(member.getName());
            memberViewHolder.memberTeam.setText(member.getTeam());
        }
    }

    @Override
    public int getItemCount() {
        return memberList == null ? 0 : memberList.size() + 1;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
    }

    static class MemberViewHolder extends RecyclerView.ViewHolder {
        ImageView memberThumb;
        TextView memberName;
        TextView memberTeam;
        public MemberViewHolder(View itemView) {
            super(itemView);
            memberThumb = (ImageView) itemView.findViewById(R.id.thumb);
            memberName = (TextView) itemView.findViewById(R.id.name);
            memberTeam = (TextView) itemView.findViewById(R.id.team);
        }
    }

    static class HeaderViewHolder extends RecyclerView.ViewHolder {
        ImageView imgHeader;
        public HeaderViewHolder(View itemView) {
            super(itemView);
            imgHeader = (ImageView) itemView.findViewById(R.id.imgHeader);
        }
    }
}

Kemudian modifikasi beberapa codingan di kelas MemberFragment.java
package wim.example.com.androidheaderrecyclerview.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import wim.example.com.androidheaderrecyclerview.R;
import wim.example.com.androidheaderrecyclerview.adapter.MemberListAdapter;
import wim.example.com.androidheaderrecyclerview.model.Member;
/**
 * Created by wim on 4/12/16.
 */
public class MemberFragment extends Fragment {

    private RecyclerView listMember;
    private LinearLayoutManager linearLayoutManager;
    private MemberListAdapter memberListAdapter;
    protected Context context;

    public static MemberFragment newInstance(){
        return new MemberFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_member, container, false);
        listMember = (RecyclerView) rootView.findViewById(R.id.listMember);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        linearLayoutManager = new LinearLayoutManager(context);
        memberListAdapter = new MemberListAdapter();
        listMember.setLayoutManager(linearLayoutManager);
        listMember.setAdapter(memberListAdapter);
        loadData();
    }

    private void loadData(){
        List<Member> memberList = new ArrayList<>();
        Member member;
        int thumb[] = {R.drawable.acha, R.drawable.yupi, R.drawable.della,
                R.drawable.kinal, R.drawable.uty, R.drawable.shafa,
                R.drawable.hanna, R.drawable.lidya, R.drawable.nadila,
                R.drawable.nat, R.drawable.sisil, R.drawable.viny,
                R.drawable.chika_chan, R.drawable.ikha, R.drawable.ayen,
                R.drawable.saktia, R.drawable.dudut, R.drawable.yona};
        String name[] = {"Alicia Chanzia", "Cindy Yuvia", "Della Delila", "Devi Kinal Putri",
                "Dwi Putri Bonita", "Fakhriyani Shafariyanti", "Jennifer Hanna", "Lidya Maulida Djuhandar",
                "Nadila Cindi Wantari", "Natalia", "Priscillia Sari Dewi", "Ratu Vienny Fitrilya",
                "Rina Chikano", "Riskha Fairunissa", "Rona Anggreani", "Saktia Oktapyani",
                "Sinka Juliani", "Viviyona Apriani"};
        String motto[] = {"Hap!Tangkap Aku!", "Mau Kemana Kita?", "Future Processor", "K3bahagiaan Depi",
                "Different", "Shafa Disana?", "Target", "Banyak Mau", "Yossha Ikuzo!", "Spicy Hot",
                "Yuk Isi Batre Senter", "#KitaBisa", "Yuk.. Kita Dangdutan!", "Nothing Gonna Stop Us Now",
                "Stand Up!", "Saktia Dalam Jiwa", "Berarti Dalam Hidup", "Life In Technicolor"};
        for(int i=0; i < thumb.length; i++){
            member = new Member();
            member.setId(i+1);
            member.setName(name[i]);
            member.setTeam(motto[i]);
            member.setThumb(thumb[i]);
            memberList.add(member);
        }
        memberListAdapter.addAll(memberList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}

Build dan jalankan maka hasilnya seperti ini.


Nice work !

Foto dan gambar hanya sebagai sampel, abaikan saja :v

Source code lengkap bisa dilihat di https://github.com/wimsonevel/AndroidHeaderRecyclerView

Sekian dan semoga bermanfaat.
Happy Coding :)

Share this :

Previous
Next Post »
0 Komentar

Penulisan markup di komentar
  • Silakan tinggalkan komentar sesuai topik. Komentar yang menyertakan link aktif, iklan, atau sejenisnya akan dihapus.
  • Untuk menyisipkan kode gunakan <i rel="code"> kode yang akan disisipkan </i>
  • Untuk menyisipkan kode panjang gunakan <i rel="pre"> kode yang akan disisipkan </i>
  • Untuk menyisipkan quote gunakan <i rel="quote"> catatan anda </i>
  • Untuk menyisipkan gambar gunakan <i rel="image"> URL gambar </i>
  • Untuk menyisipkan video gunakan [iframe] URL embed video [/iframe]
  • Kemudian parse kode tersebut pada kotak di bawah ini
  • © 2015 Simple SEO ✔

Ads