我们可以从RecyclerView的getItemCount()中获得两种返回类型吗?

时间:2018-08-03 22:50:57

标签: java android android-studio android-recyclerview

这是我的代码。当我说返回data1();它运行正常,但当我尝试返回data1()+ data3();它给了我indexOutofBound例外,我不知道原因。有人可以帮我找到此错误的原因吗?
这是我的MainActivity类代码

 String[] data={"ok","this"};
int []images_id = new int[2];
    for(int i=0; i<2; i++){
        images_id[i] = getResources().getIdentifier("drawable/"+"candy_"+i, null, getPackageName());
    }
    ArrayList ok=new ArrayList();
    for (int y=0;y<data.length;y++)
    {
         ok.add(data[y]);
    }
    recyclerView.setLayoutManager(new LinearLayoutManager(getParent()));
    RecyclerWorkclass recyclerWorkclass=new RecyclerWorkclass(this,data,images_id);
    recyclerView.setAdapter(recyclerWorkclass);

现在这是我的RecyclerView类代码

   ArrayList data1,data3;
Context context;
LayoutInflater inflater;
public RecyclerWorkclass(Context context,String[] dataoftext,int[] data2)
{
    inflater= LayoutInflater.from(context);
    this.context=context;
    data1=new ArrayList();
    data3=new ArrayList();
    for (int y=0;y<data2.length;y++)
    {
        this.data3.add(data2[y]);
    }
    for (int i=0;i<dataoftext.length;i++)
    {
        data1.add(dataoftext[i]);
    }
    Toast.makeText(context,"size is"+data3.size(),Toast.LENGTH_LONG).show();
}
@Override
public MyAdapter onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.recyclerwork_txt,parent,false);
    MyAdapter myAdapter=new MyAdapter(view);
    Toast.makeText(context,"view is "+viewType,Toast.LENGTH_LONG).show();
    return myAdapter;
}
@Override
public void onBindViewHolder(MyAdapter holder, int position) {
    holder.imageView.setImageResource((Integer) data3.get(position));
    holder.textView.setText((String)data1.get(position));
}
@Override
public int getItemCount() {
    return data1.size();
}
public class MyAdapter extends RecyclerView.ViewHolder {
    TextView textView;
    ImageView imageView;
    public MyAdapter(View itemView) {
        super(itemView);
        textView=itemView.findViewById(R.id.textview_phonecompany);
        imageView=itemView.findViewById(R.id.imageView2);}}
}

此代码工作正常,但当我说

return data1.size() + data3.size();

它显示索引超出范围错误。为什么呢?

1 个答案:

答案 0 :(得分:0)

因为在将data1.size()data3.size()放入getItemCount()中时,您与onBindViewHolder()并不亲密,可以随时RecyclerView.Adapter Doc来呼叫。

当您的adapter调用onBindViewHolder()时,他抛出此异常,因为该异常必须调用getItemCount()方法和您的两个列表,而不是getItemCount()中声明的大小。

说明

@Override
public void onBindViewHolder(MyAdapter holder, int position) {
   holder.imageView.setImageResource((Integer) data3.get(position));
   holder.textView.setText((String)data1.get(position));
}

在此position会比您的列表更多,因为您将大小增加了一倍。因此,当他尝试执行data3.get(position)时会添加此异常。