FastAdapter está aquí para simplificar la creación de adaptadores para RecyclerViews. No se preocupe por el adaptador. Simplemente escriba la lógica sobre cómo debería ser su vista/elemento, y ya está. Es ardiendo rápido, minimizando el código que necesita escribir y es fácil de extender.
¿Qué está incluido • Configuración • Guía de migración? • Utilizado por • Aplicación de muestra
La biblioteca se divide en núcleo, comunes y extensiones. Las funciones centrales se incluyen en la siguiente dependencia.
implementation " com.mikepenz:fastadapter: ${ latestFastAdapterRelease } "
implementation " androidx.appcompat:appcompat: ${ androidX } "
implementation " androidx.recyclerview:recyclerview: ${ androidX } "El soporte expandible se incluye y se puede agregar a través de esto
implementation " com.mikepenz:fastadapter-extensions-expandable: ${ latestFastAdapterRelease } "Muchas clases de ayuda se incluyen en la siguiente dependencia.
implementation " com.mikepenz:fastadapter-extensions-binding: ${ latestFastAdapterRelease } " // view binding helpers
implementation " com.mikepenz:fastadapter-extensions-diff: ${ latestFastAdapterRelease } " // diff util helpers
implementation " com.mikepenz:fastadapter-extensions-drag: ${ latestFastAdapterRelease } " // drag support
implementation " com.mikepenz:fastadapter-extensions-paged: ${ latestFastAdapterRelease } " // paging support
implementation " com.mikepenz:fastadapter-extensions-scroll: ${ latestFastAdapterRelease } " // scroll helpers
implementation " com.mikepenz:fastadapter-extensions-swipe: ${ latestFastAdapterRelease } " // swipe support
implementation " com.mikepenz:fastadapter-extensions-ui: ${ latestFastAdapterRelease } " // pre-defined ui components
implementation " com.mikepenz:fastadapter-extensions-utils: ${ latestFastAdapterRelease } " // needs the `expandable`, `drag` and `scroll` extension.
// required for the ui components and the utils
implementation " com.google.android.material:material: ${ androidX } " Simplemente cree una clase que extienda el AbstractItem como se muestra a continuación. Implemente los métodos y su elemento está listo.
open class SimpleItem : AbstractItem < SimpleItem . ViewHolder >() {
var name : String? = null
var description : String? = null
/* * defines the type defining this item. must be unique. preferably an id */
override val type : Int
get() = R .id.fastadapter_sample_item_id
/* * defines the layout which will be used for this item in the list */
override val layoutRes : Int
get() = R .layout.sample_item
override fun getViewHolder ( v : View ): ViewHolder {
return ViewHolder (v)
}
class ViewHolder ( view : View ) : FastAdapter.ViewHolder<SimpleItem>(view) {
var name : TextView = view.findViewById( R .id.material_drawer_name)
var description : TextView = view.findViewById( R .id.material_drawer_description)
override fun bindView ( item : SimpleItem , payloads : List < Any >) {
name.text = item.name
description.text = item.name
}
override fun unbindView ( item : SimpleItem ) {
name.text = null
description.text = null
}
}
}
class BindingIconItem : AbstractBindingItem < IconItemBinding >() {
var name : String? = null
override val type : Int
get() = R .id.fastadapter_icon_item_id
override fun bindView ( binding : IconItemBinding , payloads : List < Any >) {
binding.name.text = name
}
override fun createBinding ( inflater : LayoutInflater , parent : ViewGroup ? ): IconItemBinding {
return IconItemBinding .inflate(inflater, parent, false )
}
} Use la dependencia de la extensión de binding en su aplicación para esto.
// create the ItemAdapter holding your Items
val itemAdapter = ItemAdapter < SimpleItem >()
// create the managing FastAdapter, by passing in the itemAdapter
val fastAdapter = FastAdapter . with (itemAdapter)
// set our adapters to the RecyclerView
recyclerView.setAdapter(fastAdapter)
// set the items to your ItemAdapter
itemAdapter.add( ITEMS ) Por defecto, el FastAdapter solo proporciona funcionalidad básica, que viene con la abstracción de los elementos como Item y Model . Y la funcionalidad general de agregar/eliminar/modificar elementos. Para habilitar selecciones , o expandibles, las extensiones proporcionadas deben activarse.
// Gets (or creates and attaches if not yet existing) the extension from the given `FastAdapter`
val selectExtension = fastAdapter.getSelectExtension()
// configure as needed
selectExtension.isSelectable = true
selectExtension.multiSelect = true
selectExtension.selectOnLongClick = false
// see the API of this class for more options. Esto requiere la extensión
fastadapter-extensions-expandable.
// Gets (or creates and attaches if not yet existing) the extension.
val expandableExtension = fastAdapter.getExpandableExtension()
// configure as needed
expandableExtension.isOnlyOneExpandedItem = true Para más detalles, desplácese hacia abajo hasta la sección ExpandableItems (bajo uso avanzado).
fastAdapter.onClickListener = { view, adapter, item, position ->
// Handle click here
false
} // just add an `EventHook` to your `FastAdapter` by implementing either a `ClickEventHook`, `LongClickEventHook`, `TouchEventHook`, `CustomEventHook`
fastAdapter.addEventHook( object : ClickEventHook < SimpleImageItem >() {
override fun onBind ( viewHolder : RecyclerView . ViewHolder ): View ? {
// return the views on which you want to bind this event
return if (viewHolder is SimpleImageItem . ViewHolder ) {
viewHolder.viewWhichReactsOnClick
} else {
null
}
}
override fun onClick ( v : View , position : Int , fastAdapter : FastAdapter < SimpleImageItem >, item : SimpleImageItem ) {
// react on the click event
}
}) // Call this in onQueryTextSubmit() & onQueryTextChange() when using SearchView
itemAdapter.filter( " yourSearchTerm " )
itemAdapter.itemFilter.filterPredicate = { item : SimpleItem , constraint : CharSequence? ->
item.name?.text.toString().contains(constraint.toString(), ignoreCase = true )
} filter() debe devolver verdadero para que los elementos se retengan y falsan para que se eliminen los elementos.
Esto requiere la extensión
fastadapter-extensions-drag.
Primero, adjunte ItemTouchHelper a RecyclerView.
val dragCallback = SimpleDragCallback ()
val touchHelper = ItemTouchHelper (dragCallback)
touchHelper.attachToRecyclerView(recyclerView) Implemente la interfaz ItemTouchCallback en su actividad y anule el método itemTouchOnMove() .
override fun itemTouchOnMove ( oldPosition : Int , newPosition : Int ): Boolean {
DragDropUtil .onMove(fastItemAdapter.itemAdapter, oldPosition, newPosition) // change position
return true
}Comience inicializando sus adaptadores:
// Header is a model class for your header
val headerAdapter = ItemAdapter < Header >()Inicializar un modelo FastAdapter:
val itemAdapter = GenericItemAdapter ()Finalmente, configure el adaptador:
val fastAdapter : GenericFastAdapter = FastAdapter . with (headerAdapter, itemAdapter) // the order defines in which order the items will show up
// alternative the super type of both item adapters can be used. e.g.:
recyclerView.setAdapter(fastAdapter) Crea un pie de página. Necesitamos esto para mostrar una barra de progreso de carga al final de nuestra lista. (No olvides pasarlo a FastAdapter.with(..) )
val footerAdapter = ItemAdapter < ProgressItem >()Tenga en cuenta que ProgressItem es proporcionado por las extensiones de Fastadapter.
recyclerView.addOnScrollListener( object : EndlessRecyclerOnScrollListener (footerAdapter) {
override fun onLoadMore ( currentPage : Int ) {
footerAdapter.clear()
footerAdapter.add( ProgressItem ())
// Load your items here and add it to FastAdapter
itemAdapter.add( NEWITEMS )
}
})Para ver el tutorial completo y más funciones, como múltiples selectos y CAB, consulte la aplicación de muestra.
FastAdapter con Proguard FastAdapter viene con soporte para artículos expandibles. Después de agregar la dependencia configuración de la extensión Expandable a través de:
val expandableExtension = fastAdapter.getExpandableExtension() Los elementos expandibles deben implementar la interfaz IExpandable y los subtítemes de la interfaz ISubItem . Esto permite un mejor soporte. La aplicación de muestra proporciona implementaciones de muestra de esas. (Los que están en la muestra se mantienen en el modelo que les permite usarse con diferentes padres / subitems)
A partir de la forma en que se manejan SubItems y su estado, se recomienda altamente utilizar la StateManagement basada en identifier . Simplemente agregue withPositionBasedStateManagement(false) a su configuración FastAdapter .
Un elemento simple solo necesita extenderse desde AbstractExpandableItem y proporcionar al ViewHolder como tipo.
open class SimpleSubExpandableItem : AbstractExpandableItem < SimpleSubExpandableItem . ViewHolder >() {
/* *
* BASIC ITEM IMPLEMENTATION
*/
} // Consulte el SimpleSubExpandableItem.kt de la aplicación de muestra para obtener más detalles.
Mike Penz:
Mike Penz
Fabian Terhorst
Este software gratuito de código abierto también fue posible gracias a un grupo de voluntarios que pusieron muchas horas de trabajo duro. Consulte el archivo contribuyente.md para obtener más detalles.
Un agradecimiento especial a los contribuyentes muy activos que agregaron muchas mejoras a esta biblioteca.
Copyright 2021 Mike Penz
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.