知道原理后,为RecyclerView实现同时带header和footer也就分分钟的事情了
你可以把GridLayoutManager(this, 3)中的第二个参数设置为1,那就变成一个带header和footer的ListView了。
注意,这里header和footer可以为null(没人规定一定要设置header或footer的,呵呵)
import java.util.ArrayList;
import java.util.List;
import com.example.test.R;
import com.widget.view.HeaderFooterAdapter.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* 为了用RecyclerView创建一个带header的grid:
1,定义一个具有两种view类型的adapter,一个为header一个为普通item。
2,inflate一个header,把它传递给adapter。
3,重写GridLayoutManager中的setSpanSizeLookup,在header所处的位置返回和span count(列数)相等的 span size。
* @author Administrator
*
*/
public class HeaderFooterAdapter extends RecyclerView.Adapter {
private static final int ITEM_VIEW_TYPE_HEADER = 0;
private static final int ITEM_VIEW_TYPE_ITEM = 1;
private static final int ITEM_VIEW_TYPE_FOOTER = 2;
private final View header;
private final View footer;
private final List labels;
private int headerCount=0;
private int footerCount=0;
public HeaderFooterAdapter(View header, View footer,int count) {
headerCount=header == null?0:1;
footerCount=footer == null?0:1;
this.header = header;
this.footer = footer;
this.labels = new ArrayList(count);
for (int i = 0; i
View header = LayoutInflater.from(this).inflate(R.layout.header_view, recyclerView, false);
View footer = LayoutInflater.from(this).inflate(R.layout.footer_view, recyclerView, false);
final HeaderFooterAdapter adapter = new HeaderFooterAdapter(header,footer, 30);
adapter.setOnItemClickLitener(new HeaderFooterAdapter.OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
// TODO Auto-generated method stub
if(adapter.isHeader(position)){
Toast.makeText(context, "header clicked", Toast.LENGTH_SHORT).show();
}else if(adapter.isFooter(position)){
Toast.makeText(context, "footer clicked", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "header item "+position, Toast.LENGTH_SHORT).show();
}
}
});
final GridLayoutManager manager = new GridLayoutManager(this, 3);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if(adapter.isHeader(position)||adapter.isFooter(position)){
return manager.getSpanCount();
}
return 1;
}
});
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(adapter);
你必须了解的RecyclerView的五大开源项目-解决上拉加载、下拉刷新和添加Header、Footer等问题
http://www.see-source.com/blog/300000035/1463.html
滑动到顶部/底部 可拉伸回弹的ListView与ScrollView
https://github.com/teisun/SunmiUI
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net