我正在尝试使用简单的String数据填充RecyclerView,但recyclerView.setAdapter(adapter);
会出错。问题是什么?
我是recyclerview的新手。
RecyclerView recyclerView;
String []data = {"ankush", "kapoor"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
答案 0 :(得分:13)
您必须为RecyclerView创建自定义Adapter类。以下是RecyclerView自定义适配器类的示例:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
private LayoutInflater inflater;
private Context context;
<your string array list>
public CustomAdapter(Context context,<your string arraylist>) {
inflater = LayoutInflater.from(context);
this.context = context;
this.<your string arraylist>=<your string arraylist>;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.serial_number.setText(<your string array[position]>);
}
@Override
public int getItemCount() {
return <size of your string array list>;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView serial_number;
public MyViewHolder(View itemView) {
super(itemView);
serial_number = (TextView)itemView.findViewById(R.id.serialNo_CL);
}
}
}