根据数据内容创建RecyclerView项目布局

DJ-*_*DOO 2 android android-layout recycler-adapter android-recyclerview

我正在创建数据对象的循环器视图,这些对象中的每一个都会有所不同,例如.

对象1 - 字符串标题 - 字符串描述 - 图像

Obj 2 - 字符串描述

对象3 - 图像 - 字符串链接

对象4 - 字符串描述 - 视频

等等

所以我需要动态创建项目布局以适应每个数据对象.我不想创建包含所有可能的视图和组件的项目布局,并显示和隐藏,因为我认为这是不好的做法.

所以我的问题是我需要使用onBindViewHolder中的位置从列表中访问一个对象,以便在ViewHolder类中构建我的布局.

我尝试使用我在onBindViewHolder类中调用的方法并传入我在其中向数组添加自定义视图的对象,同时在内部设置内容但这不起作用.

有谁知道如何做到这一点?

问候

Bud*_*ius 5

首先,您正确实现视图类型,如此处所述如何创建具有多种视图类型的RecyclerView? 实际上,你的问题与此重复,但我会写一些额外的组织内容来帮助你处理更多数量的持有者.

  • 在这个答案我将使用ButterKnife和Picasso图书馆因为它们很棒:http://jakewharton.github.io/butterknife/ 和http://square.github.io/picasso/

  • 在你的项目上创建一个包holders,然后在里面创建所有的视图持有者,下面是一个持有者的例子:

  • 创建一个AbstractHolder具有public void bindData(Data data)这样的话你的适配器extends RecyclerView.Adapter<AbstractHolder>:

  • 创建如下持有者:

Holder1.java

public class Holder1 extends AbstractHolder {

    // that's an example of views this would use
    @Bind(R.id.text) TextView text;
    @Bind(R.id.image) ImageView image;

    // constructor as normal:
    public Holder1(View itemView){
        super(itemView);
        ButterKnife.bind(this, itemView); // init the views
    }

    // call this from the adapter
    @Override public void bindData(Data data){
        text.setText(data.text);
        Picasso.with(itemView.getContext()).load(data.url).into(image);        
    }

    // here you create an instance of this holder,
    // this way the holder and the layout it's associated with goes together
    public static Holder1 create(ViewGroup parent){
        View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.holder1, parent, false);
        return new Holder1(root);
    }

}
Run Code Online (Sandbox Code Playgroud)
  • 然后您的适配器代码将是:

.

@Override public AbstractHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch(viewType){
            case TYPE_HOLDER_1: return Holder1.create(parent);
            case TYPE_HOLDER_2: return Holder2.create(parent);
            case TYPE_HOLDER_3: return Holder3.create(parent);
            ... carry on for all types   
        }
 }

@Override public void onBindViewHolder(AbstractHolder holder, int position) {
    Object data = getItem(position);
    holder.bindData(data);
}


// the get type would be similar to that:
@Override
public int getItemViewType(int position) {
    Object data = getItem(position);
    if( ... some condition...) return TYPE_HOLDER_1;
    else if( ... other condition...) return TYPE_HOLDER_2;
    else if( ... other condition...) return TYPE_HOLDER_3;
    ... etc ...
}
Run Code Online (Sandbox Code Playgroud)

结论:

使用此方法,您的Adapter类只是可能类型的"分发中心",每种类型"知道"如何创建自身以及如何处理其数据.

这使您的代码易于维护并且组织良好.