Monday, March 23, 2020

Android Custom Recyclerview Example

RecyclerView Android it used to build UI similar to the operation of ListView, GridView. It represents the list with different presentation styles, vertically and horizontally. It is a much better ListView support library out used in CoordinatorLayout to interact with other UI components.

How to custom recyclerview Android

Having a deeper understanding of the RecyclerView and the RecyclerViewAdapter will help a lot in writing efficient code. Let’s see what makes RecyclerView awesome. At the core, the view is known for it’s recycling ability of child views that help reduce memory usage (That’s where the name comes from). At first, RecyclerView initializes a set of child views to display a certain amount of contents in the list to fill the viewport of the screen. Once the user starts scrolling, the view which gets past the screen boundary is used to repopulate and reused at the other end, this is done by the Adapter.

Creating a Custom RecyclerView Adapter

First, we'll add the RecyclerView support library:
build.gradle (Module: app)
dependencies {
   ...
    compile 'com.android.support:recyclerview-v7:+'
}
Before attaching a Custom Adapter to the RecyclerView, make sure you have included the RecyclerView view tags in the layout (xml) file.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".ui.RestaurantsActivity">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"/>
</RelativeLayout>
And, We need one more layout file which will be used as the view for each row or item in the RecyclerView, Simply to use as a template. We’ll take an example of a simple contact list. Create a new XML layout file in res/layout/ with your desired layout design.
restaurant_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_parent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp">
    <TextView
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="5dp"/>
    <TextView
        android:id="@+id/txt_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:padding="5dp"/>
</LinearLayout>
 Create a Java Class to hold the necessary information regarding the data objects.
 public class Contact {
    private String name;
    private String number;
    public Contact(String name, String number) {
        this.name = name;
        this.number = number;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
}
Using Custom Adapters with RecyclerView
Now, we are ready to use our RestaurantListAdapter in our RestaurantsActivity. Similar to the way we previously used ListViews in conjunction with ArrayAdapters, we'll call the .setAdapter() method on our new RecyclerView to set RestaurantListAdapter as its new adapter.
Additionally, we'll need to create and set an instance of the LayoutManager the RecyclerView requires. We'll use the LinearLayoutManager.
First, we'll replace these two lines of code near the top of the file:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ContactHolder> {
    private ArrayList<Contact> contactsList;
    private Context mContext;
    public VideoListAdapter(ArrayList<Contact> contactsList, Context context) {
        this.contactsList = contactsList;
        this.mContext = context;
    }
    @Override
    public ContactHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.contact_list_item, parent, false);
        return new ContactHolder(view);
    }
    @Override
    public int getItemCount() {
        return contactList == null? 0: contactList.size();
    }
    @Override
    public void onBindViewHolder(@NonNull ContactHolder holder, final int position) {
        final Contact contact = contactList.get(position);
        holder.setContactName(contact.getName());
        holder.setContactNumber(contact.getNumber());
 
    }
    public class ContactHolder extends RecyclerView.ViewHolder {
        private TextView txtName;
        private TextView txtNumber;
     
        public ContactHolder(View itemView) {
            super(itemView);
            txtName = itemView.findViewById(R.id.txt_name);
            txtNumber = itemView.findViewById(R.id.txt_number);
        }

        public void setContactName(String name) {
            txtName.setText(name);
        }
        public void setContactNumber(String number) {
            txtNumber.setText(number);
        }
    }
}
You can either hardcode the values of the contact or asynchronously load the data into the list and pass it down to the adapter to do the job of displaying it in the RecyclerView.
public class MainActivity extends AppCompatActivity {
    private MyAdapter listAdapter;
    private ArrayList<Contact> contactsList = new ArrayList<>();
    private RecyclerView recycler;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recycler = findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(layoutManager);
        listAdapter = new MyAdapter(contactsList, this);
        recycler.setAdapter(listAdapter);
     
        //Load the date from the network or other resources
        //into the array list asynchronously
     
        contactsList.add(new Contact("Daniel Shiffman", "778899009"));
        contactsList.add(new Contact("Jhon Doe", "778899009"));
        contactsList.add(new Contact("Jane Doe", "778899009"));
     
        listAdapter.notifyDataSetChanged();
    }
}

No comments:

Post a Comment