thorbenprimke / realm-recyclerview

A RecyclerView that is powered by Realm and lots more
555 stars 151 forks source link

Support for Multiple View Types #76

Closed lawrence615 closed 5 years ago

lawrence615 commented 8 years ago

Hi,

Is there a way I can be able to handle multiple view types?

Basically not defining one type of ViewHolder class in my adapter.

This is how am defining now

public class RealmReferralAdapter extends RealmBasedRecyclerViewAdapter<RealmReferral, RealmReferralAdapter.RealmReferralPendingVH> {

But am looking for a way I can be general on the ViewHolder definition so that on my onBindRealmViewHolder I can use a different depending on the type of data.

This is how I do it when using RecyclerView

public class BlogsCursorAdapter extends CursorRecyclerViewAdapter<RecyclerView.ViewHolder> {

Issue #48, is exactly what am looking for, but there is no sample code of how the problem was solved.

Thanks

CurtisBaldwinson commented 8 years ago

Hey Lawrence,

You can achieve this by overriding the following method inside your class RealmReferralAdapter which extends RealmBasedRecyclerViewAdapter: (In my example case, the Realm model is called "Message", so adapt as needed.)

        @Override
        public int getItemRealmViewType(int position) {
            Message thisMessage = realmResults.get(position);
            if (thisMessage.isOutgoing()) {
                return 1;
            }
            return 0;
        }

Now that we have modified the viewType integer, we can change our onCreateRealmViewHolder method accordingly to check against the viewType parameter and select the desired view. In this example, outgoing messages are shown on the right side and incoming messages on the left:

        @Override
        public ViewHolder onCreateRealmViewHolder(ViewGroup viewGroup, int viewType) {
            View v = null;
            if (viewType == 1) {
                v = inflater.inflate(R.layout.recycler_item_thread_right, viewGroup, false);
            } else {
                v = inflater.inflate(R.layout.recycler_item_thread_left, viewGroup, false);
            }
            return new ViewHolder((RelativeLayout) v);
        }