Header的布局文件
适配器
public class HeaderAdapterextends RecyclerView.Adapter {
private ListstatusList;
private ViewmHeaderView;
// 首先定义几个常量标记item的类型
public static final int ITEM_TYPE_HEADER =0;
public static final int ITEM_TYPE_CONTENT =1;
public HeaderAdapter(List statusList) {
this.statusList = statusList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
if(mHeaderView !=null && viewType ==ITEM_TYPE_HEADER)return new Holder(mHeaderView);
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview, parent,false);
return new Holder(layout);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position) {
if (getItemViewType(position)==0)return;
int pos = getRealPosition(holder);
String data =statusList.get(pos).getData();
int id =statusList.get(pos).getId();
if(holderinstanceof Holder) {
((Holder) holder).item_data.setText(data);
((Holder) holder).item_id.setText(id+"");
}
}
@Override
public int getItemCount() {
return mHeaderView ==null ?statusList.size() :statusList.size() +1;
}
@Override
public int getItemViewType(int position) {
if(mHeaderView ==null)return ITEM_TYPE_CONTENT;
if(position ==0)return ITEM_TYPE_HEADER;
return ITEM_TYPE_CONTENT;
}
public void setHeaderView(View headerView) {
mHeaderView = headerView;
notifyItemInserted(0);
}
public int getRealPosition(RecyclerView.ViewHolder holder) {
int position = holder.getLayoutPosition();
return mHeaderView ==null ? position : position -1;
}
class Holderextends RecyclerView.ViewHolder{
private TextViewitem_data;
private TextViewitem_id;
public Holder(View itemView) {
super(itemView);
if (itemView==mHeaderView)return;
item_id = itemView.findViewById(R.id.item_id);
item_data = itemView.findViewById(R.id.item_data);
}
}
}
Activity中使用
public class MainActivityextends AppCompatActivity {
private RecyclerViewmRecyclerView;
private Listdatas;
private HomeAdapteradapter;
private HeaderAdapterheaderAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
mRecyclerView = findViewById(R.id.mRecyclerView);
//数据源
List strings = initData(30);
//设置适配器
LinearLayoutManager manager=new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(manager);
headerAdapter=new HeaderAdapter(strings);
setHeader(mRecyclerView);
mRecyclerView.setAdapter(headerAdapter);
}
private void setHeader(RecyclerView view) {
View header = LayoutInflater.from(this).inflate(R.layout.item_header, view,false);
headerAdapter.setHeaderView(header);
}
private List initData(int count){
datas=new ArrayList<>();
for (int i=0;i
String s="item"+i;
Status status=new Status();
status.setData(s);
status.setId(i);
datas.add(status);
}
return datas;
}
}