首先看下自己的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'
dependencies { compile 'com.bartoszlipinski.recyclerviewheader:library:1.2.0' }
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 MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.onItemClickListener {//声明RecyclerView private RecyclerView mRecyclerview; //数据源 private Listlist; //声明Adapter MyRecyclerViewAdapter myRecyclerViewAdapter;
//声明RecyclerViewHeader对象 RecyclerViewHeader header; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//初始化RecyclerViewHeader header = 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一定要setLayoutManager mRecyclerview.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。