RecycleView添加头部和底部

实现思路

  1. 在Adapter中定义不同的布局和item状态
  2. 判断item的状态,加载对应的布局文件

实例代码

在gradle中添加下面的依赖

compile 'com.android.support:recyclerview-v7:23.1.0'
compile 'com.android.support:cardview-v7:23.1.0'

布局文件

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gjg.learn.recycleview_head_foot.MainActivity">

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

   android.support.v7.widget.RecyclerView>
RelativeLayout>

rv_header.xml


<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cv_header"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="6dp"
    app:cardElevation="4dp"
    app:cardBackgroundColor="#4CAF50"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="header"
            android:id="@+id/tv_header"
            android:textSize="30sp"
            android:textColor="#ffffff"
            android:padding="4dp"
            android:layout_margin="8dp"/>
    LinearLayout>

android.support.v7.widget.CardView>

rv_footer.xml


<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cv_footer"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="6dp"
    app:cardElevation="4dp"
    app:cardBackgroundColor="#E91E63"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="footer"
            android:id="@+id/tv_footer"
            android:textSize="30sp"
            android:textColor="#ffffff"
            android:padding="4dp"
            android:layout_margin="8dp"/>
    LinearLayout>

android.support.v7.widget.CardView>

rv_item.xml


<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cv_item"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="6dp"
    app:cardElevation="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="item"
            android:id="@+id/tv_content"
            android:textSize="22sp"
            android:padding="4dp"
            android:layout_margin="8dp"/>
    LinearLayout>

android.support.v7.widget.CardView>

java实现

MainActivity.java

package com.gjg.learn.recycleview_head_foot;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private HeaderBottomAdapter adapter;    
    private LinearLayoutManager layoutManager;
    StaggeredGridLayoutManager staggeredGridLayoutManager;
    //模拟数据
    public String [] texts={"java","python","C++","Php",".NET",
            "js","Ruby","Swift","OC","C","html","css",
            "C#","嵌入式"

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
        adapter=new HeaderBottomAdapter(this,texts);
        //线性布局
        layoutManager=new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        initEvent();

    }

    private void initEvent() {
        adapter.setOnItemClickListener(new HeaderBottomAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, "你点击了"+((position==0)?"header":((position==texts.length+1)?"footer":texts[position-1])),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(MainActivity.this, "你长按了"+((position==0)?"header":((position==texts.length+1)?"footer":texts[position-1])),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

HeaderBottomAdapter.java

package com.gjg.learn.recycleview_head_foot;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Junguang_Gao on 2016/11/24.
 */
public class HeaderBottomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //item类型
    public static final int ITEM_TYPE_HEADER = 0;
    public static final int ITEM_TYPE_CONTENT = 1;
    public static final int ITEM_TYPE_BOTTOM = 2;
    //item的高度
    private List mHeights;

    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private String[] datas;
    private int mHeaderCount=1;//头部View个数
    private int mBottomCount=1;//底部View个数
    public HeaderBottomAdapter(Context context,String[] datas) {
        mContext = context;
        this.datas=datas;
        mLayoutInflater = LayoutInflater.from(context);

    }
    //判断当前item是否是HeadView
    public boolean isHeaderView(int position) {
        return mHeaderCount != 0 && position < mHeaderCount;
    }
    //内容长度
    public int getContentItemCount(){
        return datas.length;
    }
    //判断当前item是否是FooterView
    public boolean isBottomView(int position) {
        return mBottomCount != 0 && position >= (mHeaderCount + getContentItemCount());
    }
    //判断当前item类型
    @Override
    public int getItemViewType(int position) {
        int dataItemCount = getContentItemCount();
        if (mHeaderCount != 0 && position < mHeaderCount) {
            //头部View
            return ITEM_TYPE_HEADER;
        } else if (mBottomCount != 0 && position >= (mHeaderCount + dataItemCount)) {
            //底部View
            return ITEM_TYPE_BOTTOM;
        } else {
            //内容View
            return ITEM_TYPE_CONTENT;
        }
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType ==ITEM_TYPE_HEADER) {
            return new HeaderViewHolder(mLayoutInflater.inflate(R.layout.rv_header, parent, false));
        } else if (viewType == ITEM_TYPE_CONTENT) {
            return new ContentViewHolder(mLayoutInflater.inflate(R.layout.rv_item, parent, false));
        } else if (viewType == ITEM_TYPE_BOTTOM) {
            return new BottomViewHolder(mLayoutInflater.inflate(R.layout.rv_footer, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderViewHolder) {


        } else if (holder instanceof ContentViewHolder) {


            ((ContentViewHolder) holder).textView.setText(datas[position - mHeaderCount]);
        } else if (holder instanceof BottomViewHolder) {

        }

        // 如果设置了回调,则设置点击事件
        if (mOnItemClickListener != null)
        {
            //itemView:ViewHolder的一个item
            holder.itemView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, pos);

                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener()
            {
                @Override
                public boolean onLongClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemLongClick(holder.itemView, pos);
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mHeaderCount + getContentItemCount() + mBottomCount;
    }

    //内容 ViewHolder
    public static class ContentViewHolder extends RecyclerView.ViewHolder {
        private TextView textView;

        public ContentViewHolder(View itemView) {
            super(itemView);
            textView=(TextView)itemView.findViewById(R.id.tv_content);
        }
    }
    //头部 ViewHolder
    public static class HeaderViewHolder extends RecyclerView.ViewHolder {
        public HeaderViewHolder(View itemView) {
            super(itemView);
        }
    }
    //底部 ViewHolder
    public static class BottomViewHolder extends RecyclerView.ViewHolder {
        public BottomViewHolder(View itemView) {
            super(itemView);
        }
    }

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

    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }
}

实现效果(LinearLayout)

RecycleView添加头部和底部_第1张图片RecycleView添加头部和底部_第2张图片

表格布局的实现

将上面的线性布局的代码改成下面的代码

        gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);//这里用线性宫格显示 类似于grid view
        mRecyclerView.setAdapter(adapter );

        //设置头部和底部的item单独占据一行
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {

                return (adapter.isHeaderView(position) || adapter.isBottomView(position)) ? gridLayoutManager.getSpanCount() : 1;
            }
        });

实现效果

RecycleView添加头部和底部_第3张图片 RecycleView添加头部和底部_第4张图片

瀑布流的实现

将代码改为下面的代码

        staggeredGridLayoutManager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(staggeredGridLayoutManager);
        mRecyclerView.setAdapter(adapter);

并在构造方法中存储item的高度

        mHeights = new ArrayList();
        for (int i = 0; i < datas.length; i++)
        {
            mHeights.add( (int) (100 + Math.random() * 300));
        }

将onBindViewHolder改为下面:

if (holder instanceof HeaderViewHolder) {
            // 获取cardview的布局属性,记住这里要是布局的最外层的控件的布局属性,如果是里层的会报cast错误
            StaggeredGridLayoutManager.LayoutParams slp = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            // 最最关键一步,设置当前view占满列数,这样就可以占据两列实现头部了
            slp.setFullSpan(true);

        } else if (holder instanceof ContentViewHolder) {
            ViewGroup.LayoutParams lp = ((ContentViewHolder) holder).textView.getLayoutParams();
            lp.height = mHeights.get(position-1);
            ((ContentViewHolder) holder).textView.setLayoutParams(lp);

            ((ContentViewHolder) holder).textView.setText(datas[position - mHeaderCount]);
        } else if (holder instanceof BottomViewHolder) {
            StaggeredGridLayoutManager.LayoutParams slp = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            slp.setFullSpan(true);
        }

实现效果

RecycleView添加头部和底部_第5张图片 RecycleView添加头部和底部_第6张图片

你可能感兴趣的:(【Android学习点滴】)