android - Android ImageView 通过代码更改 maxHeight 属性
问题描述
我有一个可滚动的视图,我在其中以编程方式插入各种视图。有些视图是文本字段,有些是图像。
我插入的大多数图像都是水平图像,但有些图像是垂直的。对于垂直图像,我想以编程方式修改 ImageView 的 maxHeight 属性。所以我做了一个近似检查 if(height > (width * 1.3) )
这是我的 Imageview xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:maxHeight="200dp"
android:scaleType="fitCenter" />
这是我的代码:
if (h > (1.3 * w)) {
imageView.setMaxHeight(500);
}
但这不起作用。谁能告诉我为什么以及解决方案是什么?
解决方案
由于您的值 500 是像素值。所以,我认为你需要将 500 转换为对应的 dp 值。尝试使用这个:
private int dpToPx(int dp, Activity activity) {
Resources r = activity.getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
并将您的代码更改为:
if (h > (1.3 * w)) {
imageView.setMaxHeight(dpToPx(500, this));
}
推荐阅读
- java - Spring Cloud Gateway 中的路由顺序
- c# - 如何修复python浮点数指数结果
- javascript - 根据对象数组中的条目将css类添加到循环生成的元素中
- c# - 如何使用 Web 服务在数据库中插入数据?
- javascript - 简单堆积的行图
- java - 在 appium 中使用 x,y 坐标点击时可以收集元素的属性吗?
- reactjs - 有时我没有道具时如何为 onChange 添加功能?
- swift - Swift:写入数据如何知道何时完成 Cocoa
- angular - 使用 ngClass 动画更改类状态
- parameters - 避免重载解析中的歧义