【问题标题】:RecyclerView with different Cardlayouts具有不同 Cardlayout 的 RecyclerView
【发布时间】:2015-01-23 12:34:08
【问题描述】:

我想做的事


目前我正在玩 RecyclerViewCardView 的。现在我写了一个RecyclerView.Adapter,我可以在上面多次显示相同的CardView,但内容不同——类似于ListViewBaseAdapter

现在我想用不同的CardView-Layout 写一个RecyclerView(采用Google Now 的风格)。我已经搜索了教程,但没有发现任何关于该主题的有用信息。有人知道,这需要如何实施?需要做些什么来实现这一点?

【问题讨论】:

标签: android android-cardview android-recyclerview


【解决方案1】:

要实现您想要的,您需要在您的RecyclerView.Adapter 上覆盖getItemViewType(position),您将在其中返回一个int,告诉您将使用哪种视图来表示此位置。

接下来,您将在 createViewHolder (parent,viewType) 上创建不同的 ViewHolders,这将在您的案例中保留对每个不同 CardLayout 的引用。

然后在bindViewHolder(holder, position) 上,您可以创建一个 switch 语句或 if else 案例来遍历您的可能视图列表并用数据填充它们。

示例代码如下:

public GeneralViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

    GeneralViewHolder holder;
    View v;
    Context context = viewGroup.getContext();

    if (viewType == FIRST_TYPE) {
        v = LayoutInflater.from(context)
                .inflate(R.layout.first_card, viewGroup, false);

        holder = new FirstTypeViewHolder(v); //Of type GeneralViewHolder
    } else {
        v = LayoutInflater.from(context)
                .inflate(R.layout.second_card, viewGroup, false);
        holder = new SecondTypeViewHolder(v);
    }

    return holder;
}

public void onBindViewHolder(GeneralViewHolder viewHolder, int i) {
    if(getItemViewType(i)==FIRST_TYPE) {
        FirstTypeViewHolder holder1 = (FirstTypeViewHolder)viewHolder;
    } else {
        SecondTypeViewHolder holder1 = (SecondTypeViewHolder)viewHolder;
    }
}

public int getItemViewType (int position) {
    //Some logic to know which type will come next;
    return Math.random()<0.5 ? FIRST_TYPE : SECOND_TYPE;
}

【讨论】:

  • 如何实现点击不同的布局??
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多