首先看下自己的RecyclerView是否包裹在 LinearLayout, FrameLayout, RelativeLayout.这三种布局中,否则会报错:
Currently, NOT already aligned RecyclerViewHeader can only be used for RecyclerView with a parent of one of types: LinearLayout, FrameLayout, RelativeLayout.
意思就是说RecyclerViewHeader这个东西只使用在线性布局、帧布局、相对布局包裹下的RecyclerView
例如:
activity_main布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" />
LinearLayout>
检查好上面的步骤之后,开始RecyclerViewHeader
1、首先在model层的build的dependencies中加入依赖:compile 'com.bartoszlipinski.recyclerviewheader:library:1.2.0'
[js] view plain copy
[js] view plain copy
dependencies {
compile'com.bartoszlipinski.recyclerviewheader:library:1.2.0'
}
为你的header创建一个XML布局文件:(就是你要加的头部的布局,我这里只加了一个TextView),这是一个单独的xml文件
1、创建一个布局文件
xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="100dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="header" />FrameLayout>
2、MainActivity代码
public class MainActivityextends AppCompatActivityimplements MyRecyclerViewAdapter.onItemClickListener {
//声明RecyclerViewprivate RecyclerViewmRecyclerview;//数据源 private Listlist;
//声明Adapter MyRecyclerViewAdaptermyRecyclerViewAdapter;
//声明RecyclerViewHeader对象RecyclerViewHeaderheader;@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//初始化RecyclerViewHeaderheader = RecyclerViewHeader.fromXml(this, R.layout.header);
mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview);list =new ArrayList<>();for (int i =0; i <100; i++) {list.add("这是第" + i +"条"); }myRecyclerViewAdapter =new MyRecyclerViewAdapter(list);
//使用RecyclerView一定要setLayoutManagermRecyclerview.setLayoutManager(new LinearLayoutManager(this));
// mRecyclerview.setLayoutManager(new GridLayoutManager(this,2));// mRecyclerview.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.HORIZONTAL));
//把RecyclerViewHeader赋予RecyclerView,这个一定要写在setLayoutManager之后
header.attachTo(mRecyclerview);mRecyclerview.setAdapter(myRecyclerViewAdapter);myRecyclerViewAdapter.setOnItemClickListener(this); }@Override public void onItemClick(View view,int position) { Log.d("TAG","类名==MainActivity" +"方法名==onItemClick===:" +"当前点击的是第" + position); }}
目前该库RecyclerViewHeader适用于LinearLayoutManager,GridLayoutManager和StaggeredGridLayoutManager布局的RecyclerView。
https://blog.csdn.net/sunbinkang/article/details/53024199
网友评论