所以我正在尝试使用recyclerview创建一个gridlayout,每个网格代表一个cardview。我正在测试它,试图在预期位置加载数字图像,如0,1,2 ....但这些数字只是在有线的地方不停地跳来跳去,有时会重复。我猜这是一个适配器问题。你能看看我的代码并告诉我哪里错了。
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
private Context context;
String[] numbers;
public GridAdapter(Context context){
super();
this.context=context;
}
@Override
public GridAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(GridAdapter.ViewHolder viewHolder, int i) {
String[] numbers={//contains url's for number images strating from 0};
Picasso.with(context).load(numbers[i]).into(ViewHolder.imageView);
}
@Override
public int getItemCount() {
return return numbers.length;
}
static class ViewHolder extends RecyclerView.ViewHolder{
public static ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView)itemView.findViewById(R.id.image);
}
}
}
顺便说一下,数字数组由主活动中的asynctask填充,recyclelerview和layoutmanager在onCreate中设置,而适配器在asynctask的onPostExecute中设置。
答案 0 :(得分:1)
您的ViewHolder
无效。对ImageView
的引用不应该是static
,因为您将有多个ViewHolders
列表,并且您将无法以这种方式存储引用。
修复您的ViewHolder
,它会正常运作。
请在此处查看示例:https://developer.android.com/training/material/lists-cards.html