- RecyclerView as Staggered Grid in Android With Example
- Example
- Step by Step Implementation
- TutorialsBuzz
- XML Layout
- Data Class
- Adapter and ViewHolder For RecyclerView
- Applying StaggeredGridLayoutManager To RecyclerView
- StaggeredGridLayoutManager
- Class Overview
- Summary
- Constants
- public static final int GAP_HANDLING_LAZY
- public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
- public static final int GAP_HANDLING_NONE
- public static final int HORIZONTAL
- public static final String TAG
- public static final int VERTICAL
- Public Constructors
- public StaggeredGridLayoutManager (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
- public StaggeredGridLayoutManager (int spanCount, int orientation)
- Public Methods
- public void assertNotInLayoutOrScroll (String message)
- public boolean canScrollHorizontally ()
- public boolean canScrollVertically ()
- public boolean checkLayoutParams (RecyclerView.LayoutParams lp)
- public int computeHorizontalScrollExtent (RecyclerView.State state)
- public int computeHorizontalScrollOffset (RecyclerView.State state)
- public int computeHorizontalScrollRange (RecyclerView.State state)
- public int computeVerticalScrollExtent (RecyclerView.State state)
- public int computeVerticalScrollOffset (RecyclerView.State state)
- public int computeVerticalScrollRange (RecyclerView.State state)
- public int[] findFirstCompletelyVisibleItemPositions (int[] into)
- public int[] findFirstVisibleItemPositions (int[] into)
- public int[] findLastCompletelyVisibleItemPositions (int[] into)
- public int[] findLastVisibleItemPositions (int[] into)
- public RecyclerView.LayoutParams generateDefaultLayoutParams ()
- public RecyclerView.LayoutParams generateLayoutParams (Context c, AttributeSet attrs)
- public RecyclerView.LayoutParams generateLayoutParams (ViewGroup.LayoutParams lp)
- public int getColumnCountForAccessibility (RecyclerView.Recycler recycler, RecyclerView.State state)
- public int getGapStrategy ()
- public int getOrientation ()
- public boolean getReverseLayout ()
- public int getRowCountForAccessibility (RecyclerView.Recycler recycler, RecyclerView.State state)
- public int getSpanCount ()
- public void invalidateSpanAssignments ()
- public void offsetChildrenHorizontal (int dx)
- public void offsetChildrenVertical (int dy)
- public void onDetachedFromWindow (RecyclerView view, RecyclerView.Recycler recycler)
- public void onInitializeAccessibilityEvent (AccessibilityEvent event)
- public void onInitializeAccessibilityNodeInfoForItem (RecyclerView.Recycler recycler, RecyclerView.State state, View host, AccessibilityNodeInfoCompat info)
- public void onItemsAdded (RecyclerView recyclerView, int positionStart, int itemCount)
- public void onItemsChanged (RecyclerView recyclerView)
- public void onItemsMoved (RecyclerView recyclerView, int from, int to, int itemCount)
- public void onItemsRemoved (RecyclerView recyclerView, int positionStart, int itemCount)
- public void onItemsUpdated (RecyclerView recyclerView, int positionStart, int itemCount, Object payload)
- public void onLayoutChildren (RecyclerView.Recycler recycler, RecyclerView.State state)
- public void onRestoreInstanceState (Parcelable state)
- public Parcelable onSaveInstanceState ()
- public void onScrollStateChanged (int state)
- public int scrollHorizontallyBy (int dx, RecyclerView.Recycler recycler, RecyclerView.State state)
- public void scrollToPosition (int position)
- public void scrollToPositionWithOffset (int position, int offset)
- public int scrollVerticallyBy (int dy, RecyclerView.Recycler recycler, RecyclerView.State state)
- public void setGapStrategy (int gapStrategy)
RecyclerView as Staggered Grid in Android With Example
GridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size .i.e., the height and width of each grid are equal. It shows symmetric items in the views.
Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the Grid is of varying size .i.e., their height and width may vary. It shows asymmetric items in the views. It automatically sets the item views according to its height and width.
In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user. There are three types of built-in layout managers.
- LinearLayoutManager: It is used to show item views in a vertical and horizontal list.
- GridLayoutManager: It is used to show item views grid views.
- StaggeredLayoutManager: It is used to show item views in staggered views.
We can also create a custom layout manager by RecyclerView.LayoutManager class.
StaggeredGridLayoutManager(int spanCount, int orientation)
- Creates staggered grid layout with given parameters
- The first parameter, spanCount is used to set the number of columns in a vertical orientation or the number of rows in the horizontal orientation
- The second parameter, orientation is used to set the vertical or horizontal orientation
Staggered Grid with Vertical Orientation
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
// staggeredGridLayoutManager with 3 columns and vertical orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
// setting recycler view layout to staggered grid
Staggered Grid with Horizontal Orientation
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
// staggeredGridLayoutManager with 3 rows and horizontal orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);
// setting recycler view layout to staggered grid
Example
In this example, we would store data into ArrayList which is used for populating RecyclerView. After that we set the layout manager of RecyclerView as a staggered grid view and then, we set the Adapter for RecyclerView to show item views. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
Источник
TutorialsBuzz
RecyclerView is a ViewGroup ,that display a scrolling list of elements based on large data sets (or data that frequently changes) . RecyclerView widget is more flexible and efficient version of ListView .
RecyclerView StaggeredGridLayoutManager allows to lay out items of recyclerView in a staggered grid format , Lets see example .
Project Detail
Project Name | RecyclerViewStaggeredGrid |
Package | com.tutorialsbuzz.recyclerviewstaggeredgrid |
Min Sdk Version | 22 |
Target Sdk Version | 29 |
Compile Sdk Version | 29 |
Theme | Theme.AppCompat.Light.DarkActionBar |
XML Layout
Data Class
To Load Data Into RecyclerView , We will read JSON File Kept Inside Asset folder and map it to above defined data class .
Name field from json matches to respective png file name kept inside drawable .
Adapter and ViewHolder For RecyclerView
1. Create StaggeredGrid cell layout
Create XML Layout file in res/layout and name it row_item.xml .
2. Adapter class
Create a Adapter That RecyclerView Can Use ,Create a class CustomAdapter extend it to RecyclerView.Adapter .
RecyclerView.Adapter has three abstract methods that we must override .
- onCreateViewHolder() : Inside this method we specify the layout that each item of the RecyclerView should use .onCreateViewHolder has return type of RecyclerView.ViewHolder which represent each row of recyclerView . Using Inflator get the view of above defined row_item and pass it to viewholder constructor and then return.
- onBindViewHolder() : Inside this method data will be displayed at the specified position .
- getItemCount() : Returns the total number of items in the data set held by the adapter.
3. ViewHolder
Create Inner class ViewHolder extend it to RecyclerView.ViewHolder , add bind function which takes above defined model data class object .
Applying StaggeredGridLayoutManager To RecyclerView
StaggeredGridLayoutManager is a subclass of RecyclerView.LayoutManager , A LayoutManager that lays out children in a staggered grid formation . It supports horizontal & vertical layout as well as an ability to layout children in reverse .
The Above Constructor Creates Vertical StaggeredGridLayoutManager and it takes two parameters
- spanCount : If orientation is vertical, spanCount is number of columns. If orientation is horizontal, spanCount is number of rows.
- orientation : Sets the orientation (VERTICAL HORIZONTAL).
Create an instance of StaggeredGridLayoutManager and set it to recyclerView layoutManager.
Источник
StaggeredGridLayoutManager
java.lang.Object | ||
↳ | android.support.v7.widget.RecyclerView.LayoutManager | |
↳ | android.support.v7.widget.StaggeredGridLayoutManager |
Class Overview
A LayoutManager that lays out children in a staggered grid formation. It supports horizontal & vertical layout as well as an ability to layout children in reverse.
Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, StaggeredGridLayoutManager can offset spans independently or move items between spans. You can control this behavior via setGapStrategy(int) .
Summary
Nested Classes | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
StaggeredGridLayoutManager.LayoutParams | LayoutParams used by StaggeredGridLayoutManager. |
[Expand] |
---|
Constants | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
int | GAP_HANDLING_LAZY | ||||||||||
int | GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS | When scroll state is changed to SCROLL_STATE_IDLE , StaggeredGrid will check if there are gaps in the because of full span items. | |||||||||
int | GAP_HANDLING_NONE | Does not do anything to hide gaps. | |||||||||
int | HORIZONTAL | ||||||||||
String | TAG | ||||||||||
int | VERTICAL |
Public Constructors | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Called when the LayoutManager should save its state. Smooth scroll to the specified adapter position. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Override this method if you want to support scroll bars. Called when the LayoutManager should save its state. Smooth scroll to the specified adapter position. Starts a smooth scroll using the provided SmoothScroller. Constantspublic static final int GAP_HANDLING_LAZYpublic static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANSWhen scroll state is changed to SCROLL_STATE_IDLE , StaggeredGrid will check if there are gaps in the because of full span items. If it finds, it will re-layout and move items to correct positions with animations. For example, if LayoutManager ends up with the following layout due to adapter changes: It will animate to the following state: public static final int GAP_HANDLING_NONEDoes not do anything to hide gaps. public static final int HORIZONTALpublic static final String TAGpublic static final int VERTICALPublic Constructorspublic StaggeredGridLayoutManager (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)Constructor used when layout manager is set in XML by RecyclerView attribute «layoutManager». Defaults to single column and vertical. public StaggeredGridLayoutManager (int spanCount, int orientation)Creates a StaggeredGridLayoutManager with given parameters. Parameters
Public Methodspublic void assertNotInLayoutOrScroll (String message)Checks if RecyclerView is in the middle of a layout or scroll and throws an IllegalStateException if it is. Parameters
public boolean canScrollHorizontally ()Query if horizontal scrolling is currently supported. The default implementation returns false. Returns
public boolean canScrollVertically ()Query if vertical scrolling is currently supported. The default implementation returns false. Returns
public boolean checkLayoutParams (RecyclerView.LayoutParams lp)Determines the validity of the supplied LayoutParams object. This should check to make sure that the object is of the correct type and all values are within acceptable ranges. The default implementation returns true for non-null params. Parameters
Returns
public int computeHorizontalScrollExtent (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int computeHorizontalScrollOffset (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int computeHorizontalScrollRange (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int computeVerticalScrollExtent (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int computeVerticalScrollOffset (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int computeVerticalScrollRange (RecyclerView.State state)Override this method if you want to support scroll bars. Default implementation returns 0. Parameters
Returns
public int[] findFirstCompletelyVisibleItemPositions (int[] into)Returns the adapter position of the first completely visible view for each span. Note that, this value is not affected by layout orientation or item order traversal. ( setReverseLayout(boolean) ). Views are sorted by their positions in the adapter, not in the layout. If RecyclerView has item decorators, they will be considered in calculations as well. StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those views are ignored in this method. Parameters
Returns
See Alsopublic int[] findFirstVisibleItemPositions (int[] into)Returns the adapter position of the first visible view for each span. Note that, this value is not affected by layout orientation or item order traversal. ( setReverseLayout(boolean) ). Views are sorted by their positions in the adapter, not in the layout. If RecyclerView has item decorators, they will be considered in calculations as well. StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those views are ignored in this method. Parameters
Returns
See Alsopublic int[] findLastCompletelyVisibleItemPositions (int[] into)Returns the adapter position of the last completely visible view for each span. Note that, this value is not affected by layout orientation or item order traversal. ( setReverseLayout(boolean) ). Views are sorted by their positions in the adapter, not in the layout. If RecyclerView has item decorators, they will be considered in calculations as well. StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those views are ignored in this method. Parameters
Returns
See Alsopublic int[] findLastVisibleItemPositions (int[] into)Returns the adapter position of the last visible view for each span. Note that, this value is not affected by layout orientation or item order traversal. ( setReverseLayout(boolean) ). Views are sorted by their positions in the adapter, not in the layout. If RecyclerView has item decorators, they will be considered in calculations as well. StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those views are ignored in this method. Parameters
Returns
See Alsopublic RecyclerView.LayoutParams generateDefaultLayoutParams ()Create a default LayoutParams object for a child of the RecyclerView. LayoutManagers will often want to use a custom LayoutParams type to store extra information specific to the layout. Client code should subclass RecyclerView.LayoutParams for this purpose. Returns
public RecyclerView.LayoutParams generateLayoutParams (Context c, AttributeSet attrs)Create a LayoutParams object suitable for this LayoutManager from an inflated layout resource. Parameters
Returnspublic RecyclerView.LayoutParams generateLayoutParams (ViewGroup.LayoutParams lp)Create a LayoutParams object suitable for this LayoutManager, copying relevant values from the supplied LayoutParams object if possible. Parameters
Returnspublic int getColumnCountForAccessibility (RecyclerView.Recycler recycler, RecyclerView.State state)Returns the number of columns for accessibility. Default implementation returns the number of items in the adapter if LayoutManager supports horizontal scrolling or 1 if LayoutManager does not support horizontal scrolling. Parameters
Returns
public int getGapStrategy ()Returns the current gap handling strategy for StaggeredGridLayoutManager. Staggered grid may have gaps in the layout due to changes in the adapter. To avoid gaps, StaggeredGridLayoutManager provides 2 options. Check GAP_HANDLING_NONE and GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS for details. ReturnsSee Alsopublic int getOrientation ()public boolean getReverseLayout ()Returns whether views are laid out in reverse order or not. Not that this value is not affected by RecyclerView’s layout direction. Returns
See Alsopublic int getRowCountForAccessibility (RecyclerView.Recycler recycler, RecyclerView.State state)Returns the number of rows for accessibility. Default implementation returns the number of items in the adapter if LayoutManager supports vertical scrolling or 1 if LayoutManager does not support vertical scrolling. Parameters
Returns
public int getSpanCount ()Returns the number of spans laid out by StaggeredGridLayoutManager. Returnspublic void invalidateSpanAssignments ()For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items. If you need to cancel current assignments, you can call this method which will clear all assignments and request a new layout. public void offsetChildrenHorizontal (int dx)Offset all child views attached to the parent RecyclerView by dx pixels along the horizontal axis. Parameterspublic void offsetChildrenVertical (int dy)Offset all child views attached to the parent RecyclerView by dy pixels along the vertical axis. Parameterspublic void onDetachedFromWindow (RecyclerView view, RecyclerView.Recycler recycler)Called when this LayoutManager is detached from its parent RecyclerView or when its parent RecyclerView is detached from its window. Subclass implementations should always call through to the superclass implementation. Parameters
public void onInitializeAccessibilityEvent (AccessibilityEvent event)public void onInitializeAccessibilityNodeInfoForItem (RecyclerView.Recycler recycler, RecyclerView.State state, View host, AccessibilityNodeInfoCompat info)Called by the AccessibilityDelegate when the accessibility information for a specific item should be populated. Default implementation adds basic positioning information about the item. Parameters
public void onItemsAdded (RecyclerView recyclerView, int positionStart, int itemCount)Called when items have been added to the adapter. The LayoutManager may choose to requestLayout if the inserted items would require refreshing the currently visible set of child views. (e.g. currently empty space would be filled by appended items, etc.) public void onItemsChanged (RecyclerView recyclerView)Called when notifyDataSetChanged() is triggered instead of giving detailed information on what has actually changed. public void onItemsMoved (RecyclerView recyclerView, int from, int to, int itemCount)Called when an item is moved withing the adapter. Note that, an item may also change position in response to another ADD/REMOVE/MOVE operation. This callback is only called if and only if notifyItemMoved(int, int) is called. public void onItemsRemoved (RecyclerView recyclerView, int positionStart, int itemCount)Called when items have been removed from the adapter. public void onItemsUpdated (RecyclerView recyclerView, int positionStart, int itemCount, Object payload)Called when items have been changed in the adapter and with optional payload. Default implementation calls onItemsUpdated(RecyclerView, int, int) . public void onLayoutChildren (RecyclerView.Recycler recycler, RecyclerView.State state)Lay out all relevant child views from the given adapter. The LayoutManager is in charge of the behavior of item animations. By default, RecyclerView has a non-null ItemAnimator , and simple item animations are enabled. This means that add/remove operations on the adapter will result in animations to add new or appearing items, removed or disappearing items, and moved items. If a LayoutManager returns false from supportsPredictiveItemAnimations() , which is the default, and runs a normal layout operation during onLayoutChildren(Recycler, State) , the RecyclerView will have enough information to run those animations in a simple way. For example, the default ItemAnimator, DefaultItemAnimator , will simply fade views in and out, whether they are actually added/removed or whether they are moved on or off the screen due to other add/remove operations. A LayoutManager wanting a better item animation experience, where items can be animated onto and off of the screen according to where the items exist when they are not on screen, then the LayoutManager should return true from supportsPredictiveItemAnimations() and add additional logic to onLayoutChildren(Recycler, State) . Supporting predictive animations means that onLayoutChildren(Recycler, State) will be called twice; once as a «pre» layout step to determine where items would have been prior to a real layout, and again to do the «real» layout. In the pre-layout phase, items will remember their pre-layout positions to allow them to be laid out appropriately. Also, removed items will be returned from the scrap to help determine correct placement of other items. These removed items should not be added to the child list, but should be used to help calculate correct positioning of other views, including views that were not previously onscreen (referred to as APPEARING views), but whose pre-layout offscreen position can be determined given the extra information about the pre-layout removed views. The second layout pass is the real layout in which only non-removed views will be used. The only additional requirement during this pass is, if supportsPredictiveItemAnimations() returns true, to note which views exist in the child list prior to layout and which are not there after layout (referred to as DISAPPEARING views), and to position/layout those views appropriately, without regard to the actual bounds of the RecyclerView. This allows the animation system to know the location to which to animate these disappearing views. The default LayoutManager implementations for RecyclerView handle all of these requirements for animations already. Clients of RecyclerView can either use one of these layout managers directly or look at their implementations of onLayoutChildren() to see how they account for the APPEARING and DISAPPEARING views. Parameters
public void onRestoreInstanceState (Parcelable state)public Parcelable onSaveInstanceState ()Called when the LayoutManager should save its state. This is a good time to save your scroll position, configuration and anything else that may be required to restore the same layout state if the LayoutManager is recreated. RecyclerView does NOT verify if the LayoutManager has changed between state save and restore. This will let you share information between your LayoutManagers but it is also your responsibility to make sure they use the same parcelable class. Returns
public void onScrollStateChanged (int state)RecyclerView calls this method to notify LayoutManager that scroll state has changed. Parameters
public int scrollHorizontallyBy (int dx, RecyclerView.Recycler recycler, RecyclerView.State state)Scroll horizontally by dx pixels in screen coordinates and return the distance traveled. The default implementation does nothing and returns 0. Parameters
Returns
public void scrollToPosition (int position)Scroll to the specified adapter position. Actual position of the item on the screen depends on the LayoutManager implementation. Parameters
public void scrollToPositionWithOffset (int position, int offset)Scroll to the specified adapter position with the given offset from layout start. Note that scroll position change will not be reflected until the next layout call. If you are just trying to make a position visible, use scrollToPosition(int) . Parameters
See Alsopublic int scrollVerticallyBy (int dy, RecyclerView.Recycler recycler, RecyclerView.State state)Scroll vertically by dy pixels in screen coordinates and return the distance traveled. The default implementation does nothing and returns 0. Parameters
Returns
public void setGapStrategy (int gapStrategy)Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter is different than the current strategy, calling this method will trigger a layout request. Источник |