1. 程式人生 > >框架】之可懸浮列表StickyHeadersRecyclerView

框架】之可懸浮列表StickyHeadersRecyclerView

        這是timehop的GitHub上發表的一個控制元件框架,大家可以去參考它的【GitHub】

        這裡先貼出GitHub上提供的效果圖:


        要使用這個框架,我們需要首先匯入它的依賴:

compile 'com.timehop.stickyheadersrecyclerview:library:0.4.3'
compile 'com.android.support:recyclerview-v7:24.0.0'
        這裡需要說明的是,這個框架要求SDK的最小版本不能低於14;另外,這個框架在2016年4月之後就不再更新維護了。

        下面讓我們來看一下它的使用方式:

(1)在佈局檔案中,我們仍然使用RecyclerView:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
(2)MainActivity中的程式碼如下:
package com.example.itgungnir.teststickyheadersrecyclerview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 android.widget.TextView;
import android.widget.Toast;

import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersTouchListener;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rv;

    private AnimalsHeadersAdapter adapter;
    private StickyRecyclerHeadersDecoration headersDecor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv = (RecyclerView) findViewById(R.id.rv);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        initEvent();
    }

    private void initView() {
        // 為RecyclerView設定介面卡
        adapter = new AnimalsHeadersAdapter();
        adapter.addAll(getDummyDataSet());
        rv.setAdapter(adapter);
        // 為RecyclerView新增LayoutManager
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rv.setLayoutManager(layoutManager);
        // 為RecyclerView新增Decorator裝飾器
        // 為RecyclerView中的Item新增Header頭部(自動獲取頭部ID,將相鄰的ID相同的聚合到一起形成一個Header)
        headersDecor = new StickyRecyclerHeadersDecoration(adapter);
        rv.addItemDecoration(headersDecor);
        // 為RecyclerView新增Item之間的分隔線
        rv.addItemDecoration(new DividerDecoration(this));
    }

    private void initEvent() {
        // 為RecyclerView新增普通Item的點選事件(點選Header無效)
        rv.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, adapter.getItem(position) + " Clicked", Toast.LENGTH_SHORT).show();
            }
        }));
        // 為RecyclerView新增Header的點選事件
        StickyRecyclerHeadersTouchListener touchListener = new StickyRecyclerHeadersTouchListener(rv, headersDecor);
        touchListener.setOnHeaderClickListener(new StickyRecyclerHeadersTouchListener.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(View header, int position, final long headerId) {
                Toast.makeText(MainActivity.this, "Header position: " + position + ", id: " + headerId, Toast.LENGTH_SHORT).show();
            }
        });
        rv.addOnItemTouchListener(touchListener);
    }

    // 獲取RecyclerView中展示的資料來源
    private String[] getDummyDataSet() {
        return getResources().getStringArray(R.array.animals);
    }

    // StickyHeadersRecyclerView的介面卡類
    private class AnimalsHeadersAdapter extends AnimalAdapter<RecyclerView.ViewHolder> implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_normal, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            TextView textView = (TextView) holder.itemView;
            textView.setText(getItem(position));
        }

        // 獲取當前Item的首字母,按照首字母將相鄰的Item聚集起來並新增統一的頭部
        @Override
        public long getHeaderId(int position) {
            return getItem(position).charAt(0);
        }

        // 獲取頭部佈局
        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_header, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        // 為頭部佈局中的控制元件繫結資料
        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {
            final TextView textView = (TextView) holder.itemView;
            textView.setText(String.valueOf(getItem(position).charAt(0)));
        }
    }
}
(3)AnimalAdapter類中的程式碼:
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/**
 * RecyclerView的介面卡
 */
public abstract class AnimalAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    private ArrayList<String> items = new ArrayList<String>();

    public AnimalAdapter() {
        setHasStableIds(true);
    }

    public void add(String object) {
        items.add(object);
        notifyDataSetChanged();
    }

    public void add(int index, String object) {
        items.add(index, object);
        notifyDataSetChanged();
    }

    public void addAll(Collection<? extends String> collection) {
        if (collection != null) {
            items.addAll(collection);
            notifyDataSetChanged();
        }
    }

    public void addAll(String... items) {
        addAll(Arrays.asList(items));
    }

    public void clear() {
        items.clear();
        notifyDataSetChanged();
    }

    public void remove(String object) {
        items.remove(object);
        notifyDataSetChanged();
    }

    public String getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return getItem(position).hashCode();
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
}
(4)RecyclerItemClickListener類中的程式碼:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        // do nothing
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}