O fastadapter está aqui para simplificar a criação de adaptadores para reciclViews. Não se preocupe mais com o adaptador. Basta escrever a lógica de como sua visualização/item deve ser e você terminou. É rápido, minimizando o código que você precisa escrever e é fácil de estender.
O que está incluído • Configuração • Guia de migração? • Usado por • App de amostra
A biblioteca é dividida em núcleo, bens comuns e extensões. As funções principais estão incluídas na seguinte dependência.
implementation " com.mikepenz:fastadapter: ${ latestFastAdapterRelease } "
implementation " androidx.appcompat:appcompat: ${ androidX } "
implementation " androidx.recyclerview:recyclerview: ${ androidX } "O suporte expansível está incluído e pode ser adicionado através disso
implementation " com.mikepenz:fastadapter-extensions-expandable: ${ latestFastAdapterRelease } "Muitas classes auxiliares estão incluídas na seguinte dependência.
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 } " Basta criar uma classe que estende o AbstractItem como mostrado abaixo. Implementar os métodos e seu item está pronto.
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 a dependência de extensão binding em seu aplicativo para isso.
// 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 padrão, o FastAdapter fornece apenas funcionalidade básica, que vem com a abstração de itens como Item e Model . E a funcionalidade geral de adicionar/remover/modificar elementos. Para ativar seleções ou expansíveis , as extensões fornecidas precisam ser ativadas.
// 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. Isso requer a extensão
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 mais detalhes, role para baixo até a seção ExpandableItems (em uso avançado).
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() deve retornar verdadeiro para que os itens sejam retidos e falsos para que os itens sejam removidos.
Isso requer a extensão
fastadapter-extensions-drag.
Primeiro, anexe ItemTouchHelper à RecyclerView.
val dragCallback = SimpleDragCallback ()
val touchHelper = ItemTouchHelper (dragCallback)
touchHelper.attachToRecyclerView(recyclerView) Implemente a interface ItemTouchCallback em sua atividade e substitua o método itemTouchOnMove() .
override fun itemTouchOnMove ( oldPosition : Int , newPosition : Int ): Boolean {
DragDropUtil .onMove(fastItemAdapter.itemAdapter, oldPosition, newPosition) // change position
return true
}Comece inicializando seus adaptadores:
// Header is a model class for your header
val headerAdapter = ItemAdapter < Header >()Inicialize um modelo fastadapter:
val itemAdapter = GenericItemAdapter ()Finalmente, defina o 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) Crie um Footeradapter. Precisamos que isso exiba uma barra de progresso de carregamento no final da nossa lista. (Não se esqueça de passar para FastAdapter.with(..) )
val footerAdapter = ItemAdapter < ProgressItem >()Lembre -se de que o ProgressItem é fornecido pelas extensões do 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 o tutorial completo e mais recursos, como multi-seleção e táxi, consulte o aplicativo de amostra.
FastAdapter com proguard O FastAdapter vem com suporte para itens expansíveis. Depois de adicionar a dependência, configure a extensão Expandable via:
val expandableExtension = fastAdapter.getExpandableExtension() Os itens expansíveis precisam implementar a interface IExpandable e os sub -itens a interface ISubItem . Isso permite um melhor suporte. O aplicativo de amostra fornece implementações de amostra dessas. (Aqueles na amostra são mantidos modelo que lhes permite ser usados com diferentes pais / subitems)
Desde a maneira como SubItems e seu estado são tratados, é altamente recomendável usar o StateManagement baseado em identifier . Basta adicionar withPositionBasedStateManagement(false) à sua configuração FastAdapter .
Um item simples só precisa se estender do AbstractExpandableItem e fornecer ao ViewHolder como tipo.
open class SimpleSubExpandableItem : AbstractExpandableItem < SimpleSubExpandableItem . ViewHolder >() {
/* *
* BASIC ITEM IMPLEMENTATION
*/
} // Consulte o SimpleSubExpandableItem.kt do aplicativo de amostra para obter mais detalhes.
Mike Penz:
Mike Penz
Fabian Terhorst
Esse software gratuito e de código aberto também foi possível por um grupo de voluntários que colocam muitas horas de trabalho duro nele. Consulte o arquivo colaboradores.md para obter detalhes.
Um agradecimento especial aos colaboradores muito ativos que adicionaram muitas melhorias 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.