Mostrando entradas con la etiqueta android. Mostrar todas las entradas
Mostrando entradas con la etiqueta android. Mostrar todas las entradas

jueves, 3 de septiembre de 2020

Android Recycler View and Kotlin - Loading images with Glide

English version: 

This article is meant to be a quick guide to implement Glide image loading library with Android's recycler view using Kotlin. The links to articles, Glide's github repo and more are at the end of this article.

Implementing Glide in your project is fairly simple and straight forward now a days, the first step we have to do is adding our projects dependencies as follows:

On our module build script file we'll add the following:

...
// Add this to your plug in definitions
apply plugin: 'kotlin-kapt'

...
dependencies {
...
def glideVersion = "4.4.0"
implementation "com.github.bumptech.glide:glide:$glideVersion"
kapt "com.github.bumptech.glide:compiler:$glideVersion"
...
}


This will enable the library on our project.


After adding the dependencies to the project it is quite easy to implemente, as easy as adding a couple of line in our Adapter, here is an example:

override fun onBindViewHolder(holder: FeedItemViewHolder, position: Int) {

val feedItem = getItem(position)
holder.itemView.setOnClickListener {
onClickListener.onClick(feedItem)
}
// get a reference to the image view where we'll be loading an image onto
val image =
holder.itemView.findViewById<ImageView>(R.id.image)

// pass the image view's context to the Glide's library with method to specify it's context
Glide.with(image.context)
// pass the image remote url
.load(feedItem.urlToImage)
// add the type of transition to display when loading
.transition(DrawableTransitionOptions.withCrossFade())
// and finally the reference to the image view we are going to be loading onto.
.into(image)
}


And that is about it! Going forward you would like to cache the images you've loaded to avoid making several loading request and thus, saving memory and making your app more efficient, something that is not covered in this article, but would be writing about it next time


Resources for this article:
https://bumptech.github.io/glide/int/recyclerview.html

https://www.zoftino.com/android-image-loading-using-glide-library

https://stackoverflow.com/questions/26890190/images-in-recyclerview

https://medium.com/@vlonjatgashi/using-glide-with-kotlin-5e345b557547


Versión en español:

 Este articulo tiene la intención de ser una guía rápida para implementar la librería para la carga de imágenes Glide junto con el recycler view de Android utilizando Kotlin. Los enlaces hacia los artículos, el repositorio de github de Glide's y más se encuentran al final de este artículo.


Implementar Glide en tu proyecto es bastante fácil y 
sencillo en estos días, el primer paso que tenemos que hacer es agregar las dependencias a nuestro proyecto de la siguiente maneraÑ

En archivo script de nuestro modulo agregamos lo siguiente:

...
// Agrega este plugin en tus definiciones
apply plugin: 'kotlin-kapt'
...
dependencies {
...
def glideVersion = "4.4.0"
implementation "com.github.bumptech.glide:glide:$glideVersion"
kapt "com.github.bumptech.glide:compiler:$glideVersion"
...
}


Esto habilitara la librería en nuestro proyecto.

Después de agregar las dependencias al proyecto es algo fácil de implementa, tan sencillo como agregar unas cuantas lineas en nuestro adaptador, aquí hay un ejemplo:

override fun onBindViewHolder(holder: FeedItemViewHolder, position: Int) {

val feedItem = getItem(position)
holder.itemView.setOnClickListener {
onClickListener.onClick(feedItem)
}
// obtén una referencia al image view en donde estaremos cargando la imagen
val image =
holder.itemView.findViewById<ImageView>(R.id.image)

// pasa el contexto del image view's a la librería de Glide
Glide.with(image.context)
// pasa el url remoto de la imagen
.load(feedItem.urlToImage)
// agrega el tipo de transición a desplegar cuando cargue
.transition(DrawableTransitionOptions.withCrossFade())
// y finalmente la referencia al image view en donde estaremos cargando la imagen
.into(image)
}


Y eso es todo! Más adelante sería bueno guardar cache de las imágenes ya cargadas para evitar hacer varias peticiones y así, ahorrar memoria y hacer tu app mas eficiente, algo que no esta cubierto en este artículo, pero si será algo que estaré escribiendo para la próxima vez.


Recursos para este artículo:
https://bumptech.github.io/glide/int/recyclerview.html

https://www.zoftino.com/android-image-loading-using-glide-library

https://stackoverflow.com/questions/26890190/images-in-recyclerview

https://medium.com/@vlonjatgashi/using-glide-with-kotlin-5e345b557547

miércoles, 21 de enero de 2015

Android Development: Android studio - Gradle DSL method not found: 'runProguard()'

Hello again people!

Happy new year to all of you(Late greetings). I am back for your misfortune with yet again a simple solution to a small headache, gradle on android studio, specifically when migration from the old stable release(0.8.11 correct me if I am not wrong.. that were stable and not on canary channel of course) from this ide to the new release(1.0.2 stable). I had a problem regading this migration(cause we all want the new cool stuff don't we - lolly pop ;)) when downloading, installing and configuring(I'll post about the process next week), and then opening a previous project to update to the new ide we have ourselves a little conundrum, when the project starts building we get the following error: "Gradle DSL method not found: 'runProguard()'"

  

 Which is sum is not cool because it would not let you build and run,  nor deploy or whatever you wanted to do(most actions depend on the ide building the app). So after using the search engine by choice google I found a neat and easy to implement solution with very small efford needed.

We just need to change a command in a line of the applications gradle build file in the app source folder file(we can do this with the current work space open for the app:
with:
This change is requiered on the new graddle version 2.1 using minifyEnable instead of on the previous ones it was "runProguard", this due to a change on the build systems inside ADT and ANT.  You can find more information about it on the official android developer site here and here.

After making this change save and then run graddle again to build your app:
Once built, then resyncronize gradle again click on the lynk named "sync now":
And you're set to go.

I really hope you this was usefull and you liked it, and please comment, share and follow.

other lynks consulted:
http://stackoverflow.com/questions/27016385/error26-0-gradle-dsl-method-not-found-runproguard
https://groups.google.com/forum/#!topic/adt-dev/4_-5NvxuFB0






Hola mi gente de nuevo!

Feliz año a todos ustedes(felicidades tardes). Estoy de regreso para su infortunio de nuevo con una mas solución simple a un pequeño dolor de cabeza, gradle en android especificamente cuando migramos de una versión estable(0.8.11 corrijanme si estoy en lo incorrect.. en que fue en esta versión estable y no en una canaria claro) de este ide a la nueva(1.0.2 estable). Tuve un problema en lo que respecta a esta migración(debido a que todos queremos la cosas nuevas chidas o no - lolly pop ;)) cuando descargamos, instalamos y configuramos(Voy a postear acerca del proceso la siguiente semana), y después abrimos un proyecto antereior para actualizarlo a el nuevo ide nos encontramos nosotros con un pequeño problema, cuando el proyecto comienza el proceso de construcción nosotros obtenemos el siguiente error: "Gradle DSL method not found: 'runProguard()'"

  

Lo cuál en resumen no esta nada chido porque no te permitirá construir y correr, ni desplegar o sea lo que sea que querías hacer(muchas acciones dependen de que el ide construya la aplicación). Entonces después de utilizar el buscador por elección encontre una manera fácil y limpia de implementer una solución con muy poco esfuerzo necesario.

Solo necesitamos cambiar un comando en una linea del archivo de construcción de gradle de la aplicación en el folder fuente app(podemos hacer esto en el espacio de trabajo actual abierto para la aplicación:
con:
Este cambio es requerido por la nueva versión de gradle 2.1 utilizando minifyEnable en lugar de lo que en la anterior "runProguard", Esto es debido a los cambio en el sistema de construcción dentro de ADT y ANT.  Puedes encontrar mas información acerca de ello en el sitio oficial de android developer site aquí y aquí.

Después de hacer estos cambios guardamos y después corremos gradle de nuevo para construir tu applicación de nuevo:
Una vez construido, entonces resincronizamos gradle de nuevo haciendo click en el enlace llamado "sync now":
Y ya estas listo para comenzar.

Realmente espero que hayan disfrutado de esto y que les haya sido útil y les haya gustado; y por favor comenten, compartan y siganme.


otros enlaces consultados:
http://stackoverflow.com/questions/27016385/error26-0-gradle-dsl-method-not-found-runproguard
https://groups.google.com/forum/#!topic/adt-dev/4_-5NvxuFB0