如果我有50种观点怎么办?我的适配器中应该有50个静态内部类吗? 根据{{3}},是的。
我的第一个想法是将每个viewholder内部类移动到一个单独的公共类中,但它们必须是静态的。所以将每个封装到一个公共类中,使内部类静态?有没有更好的选择?
编辑: 代码示例: 那么这将是一个很好的解决方案吗?这不也会扼杀性能吗?
public class MainViewHolder extends DragSortAdapter.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
View container;
TextView title;
//called in onCreateViewHolder in adapter
public MainViewHolder(DragSortAdapter adapter, View itemView) {
super(adapter, itemView);
container = itemView.findViewById(R.id.card_root);
title = container.findViewById(R.id.text);
}
//called by onBindViewHolder in adapter
public void setData(Data data) {
title.setText(data.title);
}
}
EDIT2: sample,用于何时返回viewholder的新实例
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new MainViewHolder(...);
case 2: return new MainViewHolderOther(...);
...
}
}
答案 0 :(得分:8)
您只能使用一个viewHolder内部类来处理许多不同的viewType。首先,您必须使用 getItemViewType(viewType)来获取项目位置 并且还必须根据viewType Position使用viewHolder。
创建一个vieHolder内部类,您可以根据项目的位置传递视图和视图类型,并按照下面的代码扩展布局。 代码示例如下。
public class Adapter extends
RecyclerView.Adapter<Adapter.MyViewholder> {
LayoutInflater inflater;
private Context context;
ArrayList<Detail> data = new ArrayList<Detail>();
public Adapter(Context context, ArrayList<Detail> getdata) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = getdata;
}
class MyViewholder extends RecyclerView.ViewHolder {
TextView txtRow, txt_rec;
public MyViewholder(View view, int type) {
super(view);
if (type == Constants.NORMAL) {
txtRow = (TextView) view
.findViewById(R.id.txtRow);
} else if (type == Constants.RECORDING) {
txt_rec = (TextView) view
.findViewById(R.id.txt_rec);
}
}
}
@Override
public int getItemCount() {
return data.size();
}
@Override
public void onBindViewHolder(MyViewholder viewholder, int position) {
int listViewItemType = getItemViewType(position);
Detail detail = data.get(listViewItemType);
if (detail.getType() == Constants.NORMAL) {
viewholder.txtRow.setText(detail.getKey());
} else if (detail.getType() == Constants.RECORDING) {
viewholder.txt_rec.setText(detail.getRecording());
}
}
@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
switch (listViewItemType) {
case 0:
view = inflater.inflate(R.layout.detail_item, parent,
false);
myViewholder = new MyViewholder(view, Constants.NORMAL);
case 2:
view = inflater.inflate(R.layout.recording, parent, false);
myViewholder = new MyViewholder(view, Constants.RECORDING);
}
return myViewholder;
}
@Override
public int getItemViewType(int position) {
return position;
}
}
希望此代码可以帮助您