Android 如何让组件的高度等于宽度

Android How to get the height equal the width of an component

我想让 ImageView 的高度等于它的宽度。我已经阅读了一些关于在 activity.xml 中使用 "app:..." 的内容。 但是,它说找不到命名空间。在那之后,我发现了一个对我不起作用的代码。

有没有人有解决这个问题的想法或建议?如果它必须以编程方式完成,如果有一个使用 Kotlin 的例子会很好。

如果你想让 ImageView 的高度等于它的宽度,

以编程方式[动态方式]:

int widthOfImage = image_view.getLayoutParams().width;
image_view.getLayoutParams().height = widthOfImage ;

参考this answer

你可以用硬编码的方式来完成:

  <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher_background"/>

或者你可以这样定义背景image_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#003778" />
<corners android:radius="6dp" />
<size android:width="100dp"
    android:height="100dp"/>
</shape>

并将其添加为 imageView 中的背景。 [记住它也是硬编码的]

您必须在 xml 文件中使用此自定义视图。

例子

<YourPackageName.SquareImageView
    android:id="@+id/squareImageview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/ic_launcher_background"/>

现在您必须在代码中绑定此视图。喜欢 Fragment 或 Activity 无论你用过什么。

示例(这是 java 中的代码,您可以在 kotlin 中更改它):-

SquareImageView imageView = findViewById(R.id. squareImageview);