Skip to content

Instantly share code, notes, and snippets.

@shekibobo
Last active April 22, 2019 15:14
Show Gist options
  • Save shekibobo/236365e168515bedf890a9e4bd04089c to your computer and use it in GitHub Desktop.
Save shekibobo/236365e168515bedf890a9e4bd04089c to your computer and use it in GitHub Desktop.
Fill a ViewGroup with items using a given layout. Easy to replace, reuses child views if possible.
/**
Copyright 2019 Joshua Kovach
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.
*/
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.core.view.get
/**
* A simple adapter implementation for [ViewGroup] to update items within a specific range of the
* child views. When called, the view will insert or remove children after [startIndex] and before
* [endOffset] using the provided layout until the number of children within that range equals the
* number of [items], and will then call [onBind] for each of the child items in that range.
*
* @param [layoutId] a layout resource id
* @param [items] a list of type [T] to be used when updating and binding the views
* @param [startIndex] index at which to begin inserting or updating child views
* @param [endOffset] number of views at the end of the LinearLayout to preserve when updating
* @param [onBind] a callback to update the view using the item at the provided index from [items]
*/
inline fun <reified T> ViewGroup.setItems(
@LayoutRes layoutId: Int,
items: List<T>,
startIndex: Int = 0,
endOffset: Int = 0,
onBind: (View, T, Int) -> Unit
) {
while (childCount < items.count() + startIndex + endOffset) {
inflate(layoutId, childCount - endOffset)
}
while (childCount > items.count() + startIndex + endOffset) {
removeViewAt(childCount - 1 - endOffset)
}
items.forEachIndexed { index, item ->
val view = get(index + startIndex)
onBind(view, item, index)
}
}
val Context.layoutInflater: LayoutInflater get() = LayoutInflater.from(this)
val View.layoutInflater: LayoutInflater get() = context.layoutInflater
fun ViewGroup.inflate(@LayoutRes layoutId: Int, attachToRoot: Boolean = false): View =
layoutInflater.inflate(layoutId, this, attachToRoot)
fun ViewGroup.inflate(@LayoutRes layoutId: Int, index: Int): View =
inflate(layoutId, false).also { addView(it, index) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment