我已经开始为图库应用编程。我希望我的图像以正方形显示,周围没有空格。我尝试了不同的方法,但是图像以各种方式拉伸或在它们周围留出空白。图片会通过Picasso加载。
MainActivity.java
...
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerView">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
images_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@+id/imageView"
android:layout_centerInParent="true"
android:scaleType="centerCrop"
android:src="@drawable/avatar" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="@+id/progressBar"/>
</RelativeLayout>
Adapter.java
...
Picasso.get()
.load(imageGalleryDataModel.getImageUrl())
.fit()
.centerCrop()
.into(holder.imageView, new Callback() {
@Override
public void onSuccess() {
holder.progressBar.setVisibility(View.GONE);
}
@Override
public void onError(Exception e) {
}
});
}
...
答案 0 :(得分:1)
您只需要更新image_item.xml
布局并使用ConstraintLayout
而不是RelativeLayout
!
如果您的项目中没有ConstraintLayout
依赖项,只需在app/build.gradle
的依赖项中添加以下行即可:
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
下一步是将image_item.xml
的布局更改为以下结构:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1:1"
android:src="@drawable/avatar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="@+id/imageView"
app:layout_constraintStart_toStartOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView" />
</android.support.constraint.ConstraintLayout>
希望这对您有所帮助。