<原文地址https://www.itbaoku.cn/post/2...;
我想在 RecyclerView 中显示 2 列,但它们像这张照片一样显示在 1 列中:
如何在 2 列中显示我的视图?
我在我的代码中尝试了 2 列:
rcv_pro.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.VERTICAL, false));
但它们不会显示在 2 列中.
我在 2 culmn 中找到了一个显示的灵魂,我可以修复它并清除此代码:" menuList_info_models.clear(); "但我现在有一个新的问题,当我清除 cod 时,我在 recyclerview 中的物品一团糟,每当我在 recyclerview 中滚动时,我的物品都会改变
public class MultiItem_Music_Adapter extends RecyclerView.Adapter { ArrayList
解决方案:
我必须创建两个ViewHolder 查看更多代码
public class MyAdapter extends RecyclerView.Adapter {
class ViewHolder0 extends RecyclerView.ViewHolder {
...
public ViewHolder0(View itemView){
...
}
}
class ViewHolder2 extends RecyclerView.ViewHolder {
...
public ViewHolder2(View itemView){
...
}
@Override
public int getItemViewType(int position) {
// Just as an example, return 0 or 2 depending on position
// Note that unlike in ListView adapters, types don't have to be contiguous
return position % 2 * 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
...
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolder0 viewHolder0 = (ViewHolder0)holder;
...
break;
case 2:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
...
break;
}
}
}
其他解决方案
你可以使用GridLayoutManager
<块引用>
将 GridLayoutManager 设置为您的 RecyclerView 下面代码
GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
recyclerView.setLayoutManager(gridLayoutManager);
这里是如何使用 GridLayoutManager 的链接 与 RecyclerView
其他解决方案
RvAdapter MultiItem_Music_Adapter ;
RecyclerView rcv_pro;
MultiItem_Music_Adapter = new MultiItem_Music_Adapter (getActivity());
rcv_pro.setLayoutManager(new GridLayoutManager(getActivity(), 2));
rcv_pro.setAdapter(MultiItem_Music_Adapter );