Sticky header recyclerview kotlin

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Sticky-header-recyclerview is an Android library that helps you create sticky headers on a RecyclerView. This is compatible with GridLayoutManager and LinearLayoutManager.

License

AcidFlow/sticky-header-recyclerview

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Java стринг в число

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Sticky-header-recyclerview is an Android library that helps you create sticky headers on a RecyclerView. This is compatible with GridLayoutManager and LinearLayoutManager.

Currently this library only support vertical scrolling.

Copyright (c) 2016 Paul Laturaze

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

Sticky-header-recyclerview is an Android library that helps you create sticky headers on a RecyclerView. This is compatible with GridLayoutManager and LinearLayoutManager.

Источник

Android RecyclerView StickyHeader without external library

There are several occasions when we need to implement sticky header for some list of data displayed in RecyclerView . And of course, Android doesn’t have a native UI component to implement this easily. There are several third-party libraries which we can use to achieve this functionality. But using third party libraries always comes at a cost. There is always a doubt of whether the library we are using will be updated for future versions or not, apart from the additional overhead of LOC and app size that these libraries add.
One simpler way of achieving this same behavior without having to use any third party library is to write a custom RecyclerView ItemDecoration and override onDrawOver(canvas: Canvas, parent: RecyclerView, state: State) function.
Below is the description on how to do that. Please feel free to customize this implementation to meet your requirements:

Custom ItemDecoration

  • RecyclerView adapter
  • Root view, e.g. the fragment’s root where the RecyclerView exists
  • Layout resource id for the header to be used
class StickyHeaderDecorationB : ViewDataBinding>( val adapter: StickyHeaderAdapter*>, root: View, @LayoutRes headerLayout: Int) : ItemDecoration()  //lazily initialize the binding instance for the header view private val headerBinding:B by lazy  DataBindingUtil.inflateB>(LayoutInflater.from(root.context), headerLayout, null, false) > override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: State)  super.onDrawOver(canvas, parent, state) /* This needs to be customized, please continue reading for the implementation */ > > 

Above is the basic structure for the custom ItemDecoration. Now we have to understand what customization goes inside the onDrawOver function.
Let’s continue customizing this function:

override fun onDrawOver(canvas: Canvas, parent: RecyclerView, sate: State)  super.onDrawOver(canvas, parent, state) val topChild = parent.getChildAt(0) val secondChild = parent.getChildAt(1) parent.getChildAdapterPosition(topChild).let  topPosition -> val header = adapter.getHeaderForCurrentPosition(topPosition) headerView.tvStickyHeader.text = header layoutHeaderView(topChild) canvas.drawHeaderView(topChild, secondChild) > > private fun layoutHeaderView(topView: View)  headerView.measure( MeasureSpec.makeMeasureSpec(topView.width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) ) headerView.layout(topView.left, 0, topView.right, headerView.measuredHeight) > private fun Canvas.drawHeaderView(topView: View, secondChild: View?)  save() translate(0f, calculateHeaderTop(topView, secondChild) headerView.draw(this) restore() > private fun calculateHeaderTop(topView: View, secondChild: View?) : Float = secondChild?.let  second -> // If there is any custom height to be added, calculate here if (secondView.findViewById(headerView.id)?.visibility != View.GONE)  secondView.top.toFloat() > else  maxOf(topView.top, 0).toFloat() > > ?: maxOf(topView.top, 0).toFloat() 

onDrawOver

  • we get the reference for the first and second item of the RecyclerView
  • we retrieve the header text for the top child
  • measure the header
  • calculate header top and draw the header

adapter.getHeaderForCurrentPosition(topPosition)

This adapter function returns the header text for the given position.
e.g.

// items is the list of objects displayed in the RecyclerView fun getHeaderForCurrentPosition(position: Int) = if (position in items.indices)  items[position] > else  "" > 

— layoutHeaderView(topView: View)

This function measures the EXACT width of the header view to be drawn. Note that the height is unspecified as we are using the header view’s measuredHeight .

— Canvas.drawHeaderView(topView: View, secondChild: View?)

This function saves the canvas, translates the canvas to the header view’s calculated top, draws the header and restores the canvas.

— calculateHeaderTop(topView: View, secondChild: View?)

This function calculates the top of the header. If second view is visible, we take reference of secondView’s top, else the header’s top is topView’s top.

Basic Use

// This custom decoration can be used in a fragment as follows class SomeFragment()  // initialization part. fragmentBinding.itemList.addItemDecoration( StickyHeaderItemDecorationViewStickyHeaderBinding>( someAdapter, fragmentBinding.root, R.layout.view_sticky_header ) ) 

Basic Scroll Behavior

When we initialize the list with the items, the header text for the first item will be displayed as soon as all data is inflated. Then as we scroll through the list, when the top of the second item (plus some threshold is optional) touches the bottom of the sticky header then the header for the second item is drawn. And this continues as we scroll up through the list.
As we scroll down through the list, the reverse behavior occurs and the header text are drawn.
The adapter class is responsible for providing the header text for any given position if the position is within bounds of the items size.

Please provide feedback in the comment section.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Easily add Sticky Headers to your RecyclerView

License

bgogetap/StickyHeaders

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Easily add Sticky Headers to your RecyclerView

Implement StickyHeaderHandler in your Presenter/Adapter/Activity or whatever class has access to your RecyclerView adapter dataset

Make sure the parent of the RecyclerView is a FrameLayout or CoordinatorLayout (this will be verified at runtime). To avoid this runtime check, you can call StickyLayoutManager#disableParentViewRestrictions . This will cause bugs with some ViewParent s, such as LinearLayout , so use with caution.

Instantiate a StickyLayoutManager and set that as the LayoutManager for your RecyclerView.

For items in your dataset that you want to act as sticky headers, implement the marker interface StickyHeader .

That’s it! See the example app for more in depth details.

Add elevation to your headers (animated in and out) on Lollipop and above:

layoutManager.elevateHeaders(true) OR layoutManager.setElevation(int dp)

Add a listener to be notified when headers are attached/re-bound or detached:

You will be passed the instance of the view that was either attached/re-bound or detached, as well as the adapter position of the data that view represents. It is important to note that the adapter position passed to headerDetached may not be the current position in the data set that the view was originally bound with. This can happen if the data has changed since that header was made sticky.

The adapter position passed in headerAttached will always be correct at that moment.

Add to your Gradle dependencies (Check badge at top for latest version):

dependencies < implementation 'com.brandongogetap:stickyheaders:0.6.2' >
Copyright 2016 Brandon Gogetap Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

About

Easily add Sticky Headers to your RecyclerView

Источник

Оцените статью