如何让TYPE_ITEM1设置GridLayoutManager,TYPE_ITEM2设置LinearLayoutManager
时间: 2024-02-03 13:02:39 浏览: 82
您可以在RecyclerView的适配器中使用getItemViewType方法来为不同类型的项目指定不同的LayoutManager。例如:
```
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_ITEM1 = 1;
private static final int TYPE_ITEM2 = 2;
@Override
public int getItemViewType(int position) {
// 根据位置返回对应的项目类型
if (position % 2 == 0) {
return TYPE_ITEM1;
} else {
return TYPE_ITEM2;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// 根据项目类型创建不同的ViewHolder
if (viewType == TYPE_ITEM1) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item1_layout, parent, false);
return new Item1ViewHolder(itemView);
} else if (viewType == TYPE_ITEM2) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item2_layout, parent, false);
return new Item2ViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// 根据项目类型绑定对应的数据
if (holder instanceof Item1ViewHolder) {
// 绑定Item1ViewHolder的数据
} else if (holder instanceof Item2ViewHolder) {
// 绑定Item2ViewHolder的数据
}
}
private class Item1ViewHolder extends RecyclerView.ViewHolder {
public Item1ViewHolder(View itemView) {
super(itemView);
// 设置GridLayoutManager
GridLayoutManager layoutManager = new GridLayoutManager(itemView.getContext(), 2);
((RecyclerView) itemView).setLayoutManager(layoutManager);
}
}
private class Item2ViewHolder extends RecyclerView.ViewHolder {
public Item2ViewHolder(View itemView) {
super(itemView);
// 设置LinearLayoutManager
LinearLayoutManager layoutManager = new LinearLayoutManager(itemView.getContext());
((RecyclerView) itemView).setLayoutManager(layoutManager);
}
}
}
```
在上面的代码中,getItemViewType方法根据位置返回不同的项目类型, onCreateViewHolder方法根据项目类型创建不同的ViewHolder, onBindViewHolder方法根据项目类型绑定对应的数据。在Item1ViewHolder和Item2ViewHolder中,分别设置GridLayoutManager和LinearLayoutManager。
阅读全文