我无法根据输入参数返回值

  • 本文关键字:参数 返回值 java android
  • 更新时间 :
  • 英文 :


我正在创建一个具有2种不同布局的回收器视图。但是当我重写getItemViewType方法时,每当我尝试根据位置参数返回值时,应用程序就会崩溃。例如,我可以用return 1;但不能用return position % 2;

public class myAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
String[] msgArray;
Context context;
public myAdapter(Context ct, String[] msg) {
msgArray = msg;
context = ct;
}
@Override
public int getItemViewType(int position) {
return 1;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = null;
switch (viewType) {
case 0: {
view = inflater.inflate(R.layout.recycler_view_template, parent, false);
return new MyViewHolder(view);
}
case 1: {
view = inflater.inflate(R.layout.chat_page_row, parent, false);
return new MyViewHolder2(view);
}
}

return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: {
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.myText2.setText(msgArray[position].substring(1));
}
case 1: {
MyViewHolder2 viewHolder = (MyViewHolder2) holder;
viewHolder.myText23.setText(msgArray[position].substring(1));
}
}
}
@Override
public int getItemCount() {
return msgArray.length;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView myText2;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
myText2 = itemView.findViewById(R.id.textView7);
}
}
public static class MyViewHolder2 extends RecyclerView.ViewHolder {
TextView myText23;
public MyViewHolder2(@NonNull View itemView) {
super(itemView);
myText23 = itemView.findViewById(R.id.msgFieldRight);
}
}
}

你试过了吗:

@Override
public int getItemViewType(int position) {  
return msgArray.get(position);
}

相关内容

  • 没有找到相关文章