Jeff
Jeff

Reputation: 451

I need an explanation of View Type

I have not found anything that explains what the View Type is and it must be used to differentiate between views to display when there are more than one, in which case one would use the viewType passed to onCreateViewHolder:

onCreateViewHolder(ViewGroup parent, int viewType)

While there exists a getItemViewType method there is no setItemViewType method.

So, it appears that the View Type is set by Android, there are only certain types.

  1. What are the native types and their values? I can't find anything that defines those natives in Android's documentation.

  2. How is it intended to define various views, such as if one recyclerview should have the red background? I have created a boolean value to identify an object that should be displayed differently but as onCreateViewHolder doesn't accept anything but the ViewGroup and int, there seems no way to do this, yet obviously others do.

I don't understand View Type at all and would appreciate a good explanation. For example, from the Android API guide for getItemViewType return value:

"integer value identifying the type of the view needed to represent the item at position. Type codes need not be contiguous."

What does that even mean? I haven't found anything that explains where it comes from or how it can be set, or even if it can be set.

Upvotes: 0

Views: 1245

Answers (2)

Gabe Sechan
Gabe Sechan

Reputation: 93561

ViewType is defined by you. Its basically an enumeration. If all of your items have the same view, you can just ignore it and return 1 for getItemViewType. If you have different views for different items, you just have to return a unique value for each view.

What each value is doesn't matter- Android doesn't know or care. It just uses it as a key in a hash lookup, to tell what type of view to recycle

Upvotes: 1

DeeV
DeeV

Reputation: 36035

  1. There are no native view types.
  2. You define the view types. Let's say you had to different types of items in a RecyclerView. One with a red background and one with a blue background. They alternated based on position. You'd do something like this:

```

/// Inside the RecyclerView.Adapter code:


   const VIEW_TYPE_BLUE = 0;
   const VIEW_TYPE_RED = 1;

   getItemViewType(int position) {
      return position % 2;
   }

   onCreateViewHolder(ViewGroup parent, int viewType) {
       if (viewType === VIEW_TYPE_BLUE) {
         // create blue view.
       } else { 
         // create red view.
       }
   }

```

This will allow you to do various customizations. It makes it easy for example, if you had a header View at the very top of the RecyclerView.

Upvotes: 3

Related Questions