我有一个 ListView 。每行都有一个图像和文本。我想缩放图像,使其适合行高,即
- 图像不应导致行高变大
- 图像高度应与行高相同
- 应计算图像宽度,以便保持原始宽高比
我想出的所有解决方案似乎都太复杂了,我认为这是一个相对常见的要求,所以我想检查一下我是否遗漏了一些东西 - 您知道如何以更简单的方式实现这一点吗?
以下是我考虑的解决方案。
解决方案 1:
ListView 项目的嵌套 View 并设置 android:layout_height="match_parent"。 图像大小已正确调整,但 ImageView 占据了宽度,就像未调整大小一样。 (见下图,我添加了黑色背景,看看ImageView占用了多少空间。)
<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">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:id="@+id/Image"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitStart"
android:background="#000000"
android:padding="1dp"/>
<TextView
android:id="@+id/Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/Image" />
</LinearLayout>
</RelativeLayout>
解决方案 2: 使用
ViewTreeObserver 观察者 = MyTextView.getViewTreeObserver() observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw(){
observer.removeOnPreDrawListener(this);
// Finding out height of TextView and then calculating width and height of image and setting size of ImageView. Of course, I could also get observer from ImageView and then just set width as height is correct
}
}
这看起来太复杂了。
解决方案 3:
使用例如 Paint.FontMetrics 来计算高度,但我还需要找出使用的字体(例如,系统一......)此外,ListView 可能有一些填充等,所以需要检索很多东西。
还有其他更简单的解决方案吗?
编辑 - 说明
图像具有最大。 size,如果达到该值,将停止进一步增加 ImageView 的大小。
最佳答案
如果您想根据宽度和高度设置 ImageView 的宽度和高度,您始终可以通过编程方式获取 TextView
的宽度和高度,然后实现自己的算法来相应地缩放 ImageView。
要从 textView 获取宽度和高度,我们将其称为 item_textView
,这非常简单:
TextView item_textView = findViewById(R.id.item_textView);
int text_width = item_textView.getWidth();
int text_height = item_textView.getHeight();
此时,您可以执行所需的任何数学运算,将 imageView 缩小到正确的大小。设置imageView的大小:
my_imageView.getLayoutParams().width = text_width/2;
my_imageView.getLayoutParams().height = text_height/2;
关于java - 设置ImageView相对于文本高度的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47875476/