gpt4 book ai didi

java - 如何让RecyclerView在模拟器中真正打印出一个ArrayList?

转载 作者:行者123 更新时间:2023-12-02 12:02:50 25 4
gpt4 key购买 nike

在 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));
}

}这是数组,也在 main 中:

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;
}

最佳答案

在 getDataList 方法中,您创建项目,但不将它们添加到 ArrayList。

关于java - 如何让RecyclerView在模拟器中真正打印出一个ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47123979/

25 4 0