I am new to android development and I am developing an app where the app downloads pictures from server and show them in a gridView. But some extra spaces are coming up when the
for those who want to do it in the xml layout (recyclerView item) file you can use a ConstraintLayout by combining
android:layout_width="match_parent"
android:layout_height="wrap_content"
and the following code for having a square item
app:layout_constraintDimensionRatio="4:4"
and don't forget to provide all the constraint that way you can set
android:layout_width="0dp"
android:layout_height="0dp"
hence the complete code will be as follow
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
>
<ImageView
android:id="@+id/img_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintDimensionRatio="4:4"
app:srcCompat="@drawable/event_placeholder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:scaleType="centerCrop"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Set height and width dynamically according to the screen size. this is the best way to get perfect result.
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
//if you need three fix imageview in width
int devicewidth = displaymetrics.widthPixels / 3;
//if you need 4-5-6 anything fix imageview in height
int deviceheight = displaymetrics.heightPixels / 4;
holder.image_view.getLayoutParams().width = devicewidth;
//if you need same height as width you can set devicewidth in holder.image_view.getLayoutParams().height
holder.image_view.getLayoutParams().height = deviceheight;
try this in adapter in getview hope you get better result in all device
EDIT: Or to set same height same as width you can set devicewidth in height also like below:
holder.image_view.getLayoutParams().height = devicewidth;