Android Arsenal – Vistas de reciclador

No vuelva a escribir un adaptador RecyclerView. ¡Ni siquiera un ViewHolder!

  • Residencia en Asociación de datos de Android
  • Escrito en Kotlin
  • Apoya Datos en tiempo real
  • No es necesario escribir el adaptador
  • No es necesario escribir ViewHolders
  • No es necesario cambiar las clases del modelo.
  • No es necesario notificar al adaptador cuando cambia el conjunto de datos
  • Admite múltiples tipos de visualización de elementos
  • Llamadas / oyentes opcionales
  • Muy rápido, sin reflejos
  • API súper fácil
  • SDK de Android mínimo: 19

Configurar

Gradle

Agréguelo en su build.gradle raíz al final de los repositorios:

allprojects {
 repositories {
  ...
  maven { url 'https://jitpack.io' }
 }
}

Agregue la dependencia al módulo build.gradle

// apply plugin: 'kotlin-kapt' // this line only for Kotlin projects

android {
    ...
    dataBinding.enabled true 
}

dependencies {
    implementation 'com.github.RaviKoradiya:LiveAdapter:1.3.2-1608532016'
    // kapt 'com.android.databinding:compiler:GRADLE_PLUGIN_VERSION' // this line only for Kotlin projects
}

Utilizar

Cree diseños para sus artículos con <layout> como root:

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable name="item" type="com.github.RaviKoradiya:LiveAdapter.item.Header"/>
    </data>
    
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@{item.text}"/>
        
</layout>

Es importante que todos los tipos de elementos tengan el mismo nombre de variable, en este caso “artículo”. Este nombre se pasa al constructor del adaptador como BR.variableName, en este caso BR.item:

ObservableList o lista simple
// Java
new LiveAdapter(listOfItems, BR.item)
           .map(Header.class, R.layout.item_header)
           .map(Point.class, R.layout.item_point)
           .into(recyclerView);
// Kotlin
LiveAdapter(listOfItems, BR.item)
           .map<Header>(R.layout.item_header)
           .map<Point>(R.layout.item_point)
           .into(recyclerView)

La lista de elementos puede ser un archivo ObservableList o LiveData<List> si quieres llevar el adaptador actualizado automáticamente cuando su contenido cambia o un simple List si no necesita utilizar esta función.

Datos en tiempo real <* >>
LiveAdapter(
            data = liveListOfItems,
            lifecycleOwner = this@MainActivity,
            variable = BR.item )
            .map<Header, ItemHeaderBinding>(R.layout.item_header) {
                areContentsTheSame { old: Header, new: Header ->
                    return@areContentsTheSame old.text == new.text
                }
            }
            .map<Point, ItemPointBinding>(R.layout.item_point) {
                areContentsTheSame { old: Point, new: Point ->
                    return@areContentsTheSame old.id == new.id
                }
            }
            .into(recyclerview)

Sugiero implementar DiffUtil ItemCallback durante el uso LiveData.

LayoutHandler

La interfaz LayoutHandler le permite utilizar diferentes diseños basados ​​en criterios más complejos. Su único método recibe el elemento y la posición y devuelve el id del recurso de diseño.

// Java sample
new LiveAdapter(listOfItems, BR.item)
           .handler(handler)
           .into(recyclerView);

private LayoutHandler handler = new LayoutHandler() {
    @Override public int getItemLayout(@NotNull Object item, int position) {
        if (item instanceof Header) {
            return (position == 0) ? R.layout.item_header_first : R.layout.item_header;
        } else {
            return R.layout.item_point;
        }
    }
};
// Kotlin sample
LiveAdapter(listOfItems, BR.item).layout { item, position ->
    when (item) {
        is Header -> if (position == 0) R.layout.item_header_first else R.layout.item_header
        else -> R.layout.item_point 
    }
}.into(recyclerView)

Gracias

Gracias a Miguel Ángel Moreno para este discurso.

Autor

Ravi Koradiya

Estoy abierto a nuevos puestos de trabajo – ¡Contáctame!

Licencia

Copyright 2020 Ravi Koradiya

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.

.

Compruebe también

Nuevos gadgets de Android y wearables en el Mobile World Congress + ¡Sintoniza un nuevo episodio de #TheAndroidShow la próxima semana!

Publicado por Anirudh Dewani, Director de Relaciones con Desarrolladores de Android Hoy, en el Mobile …

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *