我正在创建数据对象的回收器视图,每个对象都会有所不同,例如。
对象1
- 字符串标题
- 字符串描述
- 图像
对象2
- 字符串描述
对象3
- 图像
- 字符串链接
目标4
- 字符串描述
- 视频
etc
因此,我需要动态创建项目布局以适合每个数据对象。我不想创建一个包含所有可能的视图和组件的项目布局,并显示和隐藏,因为我觉得这是不好的做法。
所以我的问题是我需要使用 onBindViewHolder 中的位置访问列表中的对象,以便在 ViewHolder 类中构造我的布局。
我尝试使用在 onBindViewHolder 类中调用的方法,并传入将自定义视图添加到数组的对象,同时设置内部内容,但这不起作用。
有谁知道如何做到这一点?
Regards
首先,您要正确实现视图类型,如此处所述如何创建具有多种视图类型的RecyclerView? https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type实际上,你的问题与此重复,但我只会写一些额外的组织内容来帮助你处理大量的持有者。
在这个答案中,我将使用 ButterKnife 和 Picasso libraris,因为它们非常棒:http://jakewharton.github.io/butterknife/ http://jakewharton.github.io/butterknife/ and http://square.github.io/picasso/ http://square.github.io/picasso/
在您的项目上创建一个包holders
然后将所有视图持有者放入其中,下面是持有者的示例:
创建一个AbstractHolder
with public void bindData(Data data)
那么你的适配器extends RecyclerView.Adapter<AbstractHolder>
:
创建如下所示的持有者:
example 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);
}
}
.
@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 ...
}
结论:
使用这种方法,您的 Adapter 类只是可能类型的“分发中心”,并且每种类型“知道”如何创建自身以及如何处理其数据。
这使您的代码易于维护且组织良好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)