I am trying to populate RecyclerView with simple String data but recyclerView.setAdapter(adapter);
gives error. What's the problem?
I am new to 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); }
Adapter , much like the built-in Android ArrayAdapter , will populate the data into the RecyclerView . It also converts a Java object into an individual list item View to be inserted and displayed to the user.
Adapter base class for presenting List data in a RecyclerView , including computing diffs between Lists on a background thread. This class is a convenience wrapper around AsyncListDiffer that implements Adapter common default behavior for item access and counting.
ListAdapter gets data using a method called submitList() , which submits a list to be diffed against the current list and displayed. This means you no longer have to override getItemCount() because ListAdapter manages the list. In the Activity class, call submitList() on the Adapter and pass in the data list.
The RecyclerView is a ViewGroup that renders any adapter-based view in a similar way. It is supposed to be the successor of ListView and GridView. One of the reasons is that RecyclerView has a more extensible framework, especially since it provides the ability to implement both horizontal and vertical layouts.
You have to create a custom Adapter class for a RecyclerView. Here is the example of RecyclerView custom adapter class :
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With