将JSON数组转换为在RecyclerView中使用的步骤如下:
ArrayList<MyModel> dataList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
MyModel model = new MyModel(name, age);
dataList.add(model);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MyModel> dataList;
public MyAdapter(ArrayList<MyModel> dataList) {
this.dataList = dataList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MyModel model = dataList.get(position);
holder.nameTextView.setText(model.getName());
holder.ageTextView.setText(String.valueOf(model.getAge()));
}
@Override
public int getItemCount() {
return dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView ageTextView;
public ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.nameTextView);
ageTextView = itemView.findViewById(R.id.ageTextView);
}
}
}
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
以上是将JSON数组转换为在RecyclerView中使用的基本步骤。根据具体需求,你可能需要进行一些额外的操作,例如添加点击事件、加载图片等。
领取专属 10元无门槛券
手把手带您无忧上云