1

Tengo un RecyclerVIew que se carga con imágenes de internet, pero por algún motivo que desconozco se me añaden espacios:

introducir la descripción de la imagen aquí

Los rectángulos marcados en negro, son los que se me añaden. Mi problema va con la separación en altura de las imágenes, quiero reducirlo lo más posible.

Este es el diseño del layout:

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/tmoGris"
        android:orientation="vertical"
        android:padding="5dp">
        <ImageView
            android:id="@+id/ivPortadaPopulares"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/todo"
            tools:ignore="MissingConstraints" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

Y este es el de la actividad:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".lectortmo.LectorTmo"
    android:background="@color/tmoGris">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:background="@color/white"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/tu"
                android:textSize="25sp"
                android:text="@string/tu"
                android:textColor="@color/tmoAzul"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/manga"
                android:textSize="25sp"
                android:text="@string/manga"
                android:textColor="@color/tmoAzul"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/online"
                android:textSize="25sp"
                android:text="@string/online"
                android:textColor="@color/tmoAzul"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="3">
                <Button
                    android:id="@+id/btnPopulares"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:text="@string/tmoPopulares"
                    android:textAllCaps="false"
                    android:fontFamily="@font/roboto_regular"
                    android:textColor="@color/tmoAzul"/>
                <Button
                    android:id="@+id/btnPSeinen"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:text="@string/tmoPSeinen"
                    android:textAllCaps="false"
                    android:fontFamily="@font/roboto_regular"
                    android:textColor="@color/tmoAzul"/>
                <Button
                    android:id="@+id/btnPJosei"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@null"
                    android:text="@string/tmoPJosei"
                    android:textAllCaps="false"
                    android:fontFamily="@font/roboto_regular"
                    android:textColor="@color/tmoAzul"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp">
                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rvPopulares"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

¿Cuál sería mi error?

Dejo mi adaptador:

class TmoGridAdapterTmo(
    private var tmoClaseArrayList: ArrayList<TmoClase>,
    private val contexto: Context
) : RecyclerView.Adapter<TmoGridAdapterTmo.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        @SuppressLint("InflateParams") val view =
            LayoutInflater.from(parent.context).inflate(R.layout.grilla_populares, null)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val tmoClase = tmoClaseArrayList[position]
        Picasso.get().load(tmoClase.imagenUrl).into(holder.portadaManga)
    }

    override fun getItemCount(): Int {
        return tmoClaseArrayList.size
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var portadaManga: ImageView

        init {
            portadaManga = view.findViewById(R.id.ivPortadaPopulares)
        }
    }

    fun updateData(tmoClaseArrayList: ArrayList<TmoClase>) {
        this.tmoClaseArrayList = tmoClaseArrayList
    }
}

Y mi activity:

class LectorTmo : AppCompatActivity() {
    private val arrayTmo = ArrayList<TmoClase>()
    private val async : AsyncTaskViewModel by lazy {
        ViewModelProvider(this)[AsyncTaskViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lector_tmo)

        val grillaPopulares = findViewById<RecyclerView>(R.id.rvPopulares)
        grillaPopulares.apply {
            layoutManager = GridLayoutManager(this@LectorTmo, 3)
        }

        async.execute(
            onPreExecute = {
            }, doInBackground = {
                arrayTmo.clear()
                val url = "https://lectortmo.com/"
                try{
                    val doc = Jsoup.connect(url)
                        .userAgent("Mozilla")
                        .header("Accept", "text/html")
                        .header("Accept-Encoding", "gzip,deflate")
                        .header(
                            "Accept-Language",
                            "it-IT,en;q=0.8,en-US;q=0.6,de;q=0.4,it;q=0.2,es;q=0.2"
                        )
                        .header("Connection", "keep-alive")
                        .ignoreContentType(true)
                        .get()

                    val elementoPopular =
                        doc.select("div.row")
                            .select("div.col")
                            .select("div.tab-content")
                            .select("div#pills-populars")
                            .select("div.row")
                            .select("div.element")
                            .select("div.thumbnail")
                    Log.d("elemPop", "onCreate: $elementoPopular")
                    for(elementos in elementoPopular){
                        val imgId = elementos
                            .select("style")
                            .first()
                            .html()
                        Log.d("imgId", "onCreate: $imgId")

                        var urlImg = imgId.substring(imgId.indexOf("('") + 2, imgId.indexOf("')"))
                        Log.d("urlImg", "onCreate: $urlImg")

                        arrayTmo.add(TmoClase(urlImg, "", "", ""))
                    }
                }catch (e: Exception){
                    Log.d("async", "onCreate: " + e.message)
                }
            }, onPostExecute = {
                Log.d("ArrayTmo", "onCreate: ${arrayTmo.toArray().size}")
                try {
                    grillaPopulares.adapter = TmoGridAdapterTmo(arrayTmo, this)
                }catch (ex: Exception){
                    Log.d("LoadGrilla", "onCreate: ${ex.message}")
                }
            }
        )
    }
}

TmoClase:

class TmoClase (var imagenUrl: String, var titulo: String,var detalleUrl: String, var demografia: String)

AsyncTaskViewModel:

class AsyncTaskViewModel : ViewModel() {
    fun <R> execute(
        onPreExecute: () -> Unit,
        doInBackground: () -> R,
        onPostExecute: (R) -> Unit
    ) = viewModelScope.launch {
        onPreExecute()
        val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
            doInBackground()
        }
        onPostExecute(result)
    }
}

build.gradle Módulo:

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //Componentes/Librerías externos/as
    //CardView
    implementation 'androidx.cardview:cardview:1.0.0'
    //JSOUP
    implementation 'org.jsoup:jsoup:1.10.3'
    //Picasso
    implementation 'com.squareup.picasso:picasso:2.71828'
    //RecyclerView
    implementation 'androidx.recyclerview:recyclerview:1.2.1'

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
}

build.gradle Proyecto:

plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
6
  • 1
    Se ven 3 imagenes por renglon, cuantas imagenes pueden ir en el renglon? Se pueden deslizar las imagenes horizontalmente? Si pudieras agregar por favor también TmoClase para conocer como esta estructurado el objeto.
    – Jorgesys
    el 20 jun. 2022 a las 21:43
  • 1
    Me parece que es el reciclamiento, podrías compartirme: AsyncTaskViewModel ?
    – Jorgesys
    el 21 jun. 2022 a las 14:55
  • 1
    revisa mi respuesta y comparte tu configuración de dependencias por favor.
    – Jorgesys
    el 21 jun. 2022 a las 20:36
  • He compartido mis dependencias @Jorgesys el 22 jun. 2022 a las 15:24
  • 1
    algo que olvide preguntarte es en que versiòn de sistema operativo estas probando? es emulador o un dispositivo fisico?
    – Jorgesys
    el 26 jun. 2022 a las 17:40

1 respuesta 1

1

Revisando tu Adapter no encontré algún problema, me llamo la atención que se generaran espacios, pensé era algo en el RecyclerView, pero tampoco encontré algo diferente.

introducir la descripción de la imagen aquí

Ahora al usar el código confirmo que no hay problema aparente, pero en estos casos que se encuentran inconsistencias es generalmente debido a las actualizaciones de bibliotecas de Google, por ejemplo al actualizar las versiones de material o constraintlayout puedes encontrar este tipo de detalles.

Esta es la configuración:

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //Jsoup
    implementation 'org.jsoup:jsoup:1.10.3'
    //Picasso
    implementation 'com.squareup.picasso:picasso:2.71828'

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
}
3
  • Pues, copié las configuraciones que muestras dejando claro que también está el carview / recyclerview y pues sigo teniendo el mismo problema el 22 jun. 2022 a las 15:27
  • 1
    Gracias Franqo, no me refiero a que estén o no, el detalle esta relacionado a las versiones. Voy a revisar y te comento :D
    – Jorgesys
    el 22 jun. 2022 a las 15:32
  • Copié las mismas versiones que indicas, eso quise decir, gracias por tu tiempo :') el 22 jun. 2022 a las 15:55

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.