I load images in a recycler view but spaces appear in the bank:
Adapter:
package com.example.recyclerview;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdapterDatos extends RecyclerView.Adapter<AdapterDatos.ViewHolderDatos> {
ArrayList<String> listDatos;
public AdapterDatos(ArrayList<String> listDatos)
{
this.listDatos = listDatos;
}
@NonNull
@Override
public ViewHolderDatos onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);
return new ViewHolderDatos(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolderDatos holder, int position) {
holder.asignarDatos(listDatos.get(position));
}
@Override
public int getItemCount() {
return listDatos.size();
}
public class ViewHolderDatos extends RecyclerView.ViewHolder {
ImageView imagen;
public ViewHolderDatos(@NonNull View itemView) {
super(itemView);
imagen=(ImageView)itemView.findViewById(R.id.imagen_dato);
}
public void asignarDatos(String s) {
imagen.setImageResource(R.drawable.gato);
}
}
}
Main:
package com.example.recyclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listDatos;
RecyclerView recycler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler=(RecyclerView)findViewById(R.id.RecyclerId);
recycler.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
listDatos= new ArrayList<String>();
for (int i=0;i<3;i++)
{
listDatos.add("Dato: " + i);
}
AdapterDatos adapter=new AdapterDatos(listDatos);
recycler.setAdapter(adapter);
}
}
XMLItems:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imagen_dato"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I can see that your file
item_list.xml
indicates that you have a height defined asmatch_parent
, it should bewrap_content
, make the change:MATCH_PARENT
indicates that the view wants to be as big as its parent (less padding).WRAP_CONTENT
, indicates that the view wants to be large enough to hold its content (plus padding).Inside your Adapter, make the following change: