android - 如何根据android中的设备dpi设置与宽度成比例的高度

标签 android android-imageview dpi

我想根据不同的设备和 dpi 来固定 imageview 的高度。

<ImageView
        android:id="@+id/imgFood"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_no_img" />

到目前为止,我将高度固定为 200dp,但我想保持 1:2 的比例而不是固定大小。我知道 android 在 dp 上工作,但我无法弄清楚如何保持所有设备的比率。宽度将与父级匹配(适合设备宽度),但需要相应地更改高度。

有什么想法/建议吗?

最佳答案

你可以像这样动态设置你的高度。

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();

ll.getLayoutParams().height = width/2;
ll.getLayoutParams().width = width;
ll.requestLayout();

关于android - 如何根据android中的设备dpi设置与宽度成比例的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427507/

相关文章:

android - 将像素转换为 dp

javascript - 关闭 x-ms-webview 自动缩放

android - 我应该使用什么权限来接收 android 通知?

java - 在 Android void 中向公众传递字符串

android - 将 recyclerview 中的图片添加到新 Activity 中

android - 通过使用计时器(或处理程序)更改 ImageView 中的图像来创建动画

android - 我需要在 Android 上提供 xxhdpi 图像吗?

android - 按钮应该和最大的一样宽

android - 如何从服务调用 Activity 中的方法

java - 如何在 ImageView 中显示视频缩略图?