recyclerview固定头部
时间: 2023-09-08 19:14:40 浏览: 97
RecyclerView 可以通过使用 RecyclerView.ItemDecoration 来实现固定头部的效果。具体步骤如下:
1. 创建一个继承 RecyclerView.ItemDecoration 的类,重写 getItemOffsets() 方法,在该方法中对头部 View 进行偏移量的计算。
```java
public class HeaderItemDecoration extends RecyclerView.ItemDecoration {
private View headerView;
public HeaderItemDecoration(View headerView) {
this.headerView = headerView;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = headerView.getHeight();
}
}
}
```
2. 在 Adapter 中重写 getItemViewType() 方法,返回一个标志头部 View 的 viewType,以便在 onCreateViewHolder() 方法中判断是否需要加载头部 View。
```java
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_HEADER = 0;
private static final int VIEW_TYPE_ITEM = 1;
private View headerView;
private List<String> dataList;
public MyAdapter(View headerView, List<String> dataList) {
this.headerView = headerView;
this.dataList = dataList;
}
@Override
public int getItemViewType(int position) {
return position == 0 ? VIEW_TYPE_HEADER : VIEW_TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_HEADER) {
return new RecyclerView.ViewHolder(headerView) {};
} else {
// 创建普通的 ViewHolder
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == VIEW_TYPE_ITEM) {
// 绑定普通的 ViewHolder
}
}
@Override
public int getItemCount() {
return dataList.size() + 1; // 加上头部 View 的数量
}
}
```
3. 在 Activity 或 Fragment 中初始化 RecyclerView,并设置 Adapter 和 ItemDecoration。
```java
RecyclerView recyclerView = findViewById(R.id.recycler_view);
View headerView = LayoutInflater.from(this).inflate(R.layout.header_layout, recyclerView, false);
MyAdapter adapter = new MyAdapter(headerView, dataList);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new HeaderItemDecoration(headerView));
```
通过以上步骤,就可以实现 RecyclerView 中固定头部的效果了。
阅读全文