在Android Studio中,我必须使用ArrayList和一些图片创建RecyclerView。我遵循了一些教程和Android文档,因此我设法将可以运行的代码组合在一起。但是,除了背景颜色之外,模拟器不会显示任何内容。
所以在MyAdapter.java中我创建了一个onBindViewHolder()方法,其中数据应该提供给ViewHolder。为了让程序真正写出Arraylist,我需要更改什么?
MyAdapter.java看起来像这样:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context context;
List<DataSource> data = Collections.emptyList();
public MyAdapter(Context context, List<DataSource> tada){
this.context = context;
inflater = LayoutInflater.from(context);
this.data = tada;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.custom_row,viewGroup, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder viewHolder, int position) {
//The position of the item within the adapter's data set.
DataSource info = data.get(position);
viewHolder.text.setText(info.name);
viewHolder.icon.setImageResource(info.picid);
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView text;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.editText2);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
Log.i("MyAdapter", "MyViewHolder()" + " " + String.valueOf(getPosition()));
}
}
}
主要是这样的:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.drawerList);
myAdapter = new MyAdapter(this, getdatalist());
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
} 这是数组,也是主要的:
public List<DataSource> getdatalist(){
List<DataSource> data = new ArrayList<>();
String[] name = {"Black Pearl", "Blue Monday", "Gray Worm", "Green Lantern", "Baby Blue", "Clockwork Orange", "Purple Haze", "Red Socks", "Violet Teacher", "Yellow Claws"}
int[] icon = {R.drawable.black, R.drawable.blue, R.drawable.gray, R.drawable.green, R.drawable.light_blue, R.drawable.orange, R.drawable.purple, R.drawable.red,R.drawable.violet, R.drawable.yellow }
for(int i =0; i<name.length && i<icon.length; i++){
DataSource info = new DataSource;
info.name = name[i];
info.picid = icon[i];
}
return data;
}
答案 0 :(得分:1)
在getDataList方法中,您可以创建项目,但不要将它们添加到ArrayList。