首先看下自己的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' }
爲你的header創建一個XML佈局文件:(就是你要加的頭部的佈局,我這裏只加了一個TextView),這是一個單獨的xml文件
<?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 List<String> list;
//聲明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。