如何使用 CardView 调整图像?
Posted
技术标签:
【中文标题】如何使用 CardView 调整图像?【英文标题】:How to adapt images with CardView? 【发布时间】:2020-07-18 11:01:52 【问题描述】:我正在创建一个使用 CardView 作为我的小部件的 App Gallery,但我面临一个问题,即我的图库中的图像忽略了我想要的大小,因此它们都是重叠的,而不是为其创建边距。
我正在调整以下 android 图片库:
https://medium.com/@moforemmanuel/android-simple-image-gallery-30c0f00abe64
我想要这样的东西:
但是当我有多个图像时,运行我的代码会得到这个结果:
我基于你自己的代码可以在下面看到:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_
android:layout_>
<androidx.cardview.widget.CardView
android:layout_
android:layout_
android:layout_marginTop="1dp"
android:layout_marginLeft=".5dp"
android:layout_marginRight=".5dp"
android:layout_marginBottom=".5dp"
app:cardCornerRadius="1dp">
<FrameLayout
android:layout_
android:layout_>
<ImageView
android:id="@+id/image"
android:layout_
android:layout_
android:scaleType="center"
tools:ignore="ContentDescription" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
我应该在我的代码中进行哪些更改,以便我可以修改图像的大小并仍然保持边距,以便始终拥有自适应布局?
非常感谢!
附: 我已经尝试了 Dharmaraj 的建议,但后来我得到了以下布局:
将android:layout_width
和android:layout_height
更改为"200sp"
,它仍然重叠,如下所示:
要加载图像,我使用了这两个函数:
【问题讨论】:
重叠是指图像被裁剪了吗?? 是的,正如您在图片中看到的那样,它们都被裁剪了。 那是因为我们已经固定了 CardView 的值。可以试试把 CardView 的高宽设置成图片的高宽吗?? 但请记住,如果您根据图像调整高度和宽度,可能会占用大量屏幕空间 在原始代码(我在问题中添加链接的那个)中,开发人员使用了android:layout_width="90dp"
和android:layout_height="90dp"
【参考方案1】:
试试这个:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_
android:layout_>
<androidx.cardview.widget.CardView
android:layout_
android:layout_
android:layout_marginTop="1sp"
android:layout_marginLeft="1sp"
android:layout_marginRight="1sp"
android:layout_marginBottom="1Sp"
app:cardCornerRadius="1sp">
<RelativeLayout
android:layout_
android:layout_
android:layout_margin="5sp>
<ImageView
android:id="@+id/image"
android:layout_
android:layout_
android:layout_center="true" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
为了方便起见,我基本上已将 FrameLayout 替换为 RelativeLayout,请为卡片视图分配恒定的高度和宽度。不要为主布局分配恒定的高度和宽度。这为我解决了这个问题。如果您需要在 cmets 中进行更多说明,请告诉我。
顺便说一下,图像中的属性android:src
丢失了。还是动态分配图片?
【讨论】:
它没有按我的意愿工作,我也尝试更改 layout_width 和 layout_height,但图像仍然重叠。我将更新问题,以便您了解发生了什么。 @Codewraith 您能说一下您是如何向其中添加图像的吗?我在那里看不到android:src
。您是否正在动态尝试为更多图像创建此类卡片视图?
我添加了我如何加载图像的问题。
如果您需要,可以查看我用作基础的代码,基本上是来自 Medium 的代码(我已在问题中添加了链接)。
@Codewraith 一定要看看以上是关于如何使用 CardView 调整图像?的主要内容,如果未能解决你的问题,请参考以下文章
如何修剪左下角的图像以在 XML 中的 cardview 中获得这样的半圆形,在底部修剪图像?附上图片