是否可以在 XML LinearLayout 中添加一个 ImageView,其宽度为屏幕宽度的 15%,高度也完全相同?
我尝试使用当用户点击 map 上的标记时显示的对话框代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_info_bubble"
android:orientation="vertical">
.
. [some more content here]
.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100">
<ImageView
android:id="@+id/favorite"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:layout_weight="15"
android:layout_marginEnd="5dp" />
</LinearLayout>
</LinearLayout>
但是有两个问题:
问题 1: android:layout_weight="15"占对话框宽度的 15%,而不是屏幕的宽度,这是一个大问题,因为对话框有时或多或少宽度取决于其内容。
问题2:宽度是15%可以,但是高度是图片的真实高度。我不知道如何使它的高度与宽度完全相同。它是一个方形图像,所以我试着让它尊重它的比例,将 wrap_content 放在高度上并调整 adjustViewBounds=true 但它没有用。
问题 3:ImageView 没有居中,而是左对齐。我需要它居中。
如何使用 XML 而不是 Java 代码来实现这一点?
最佳答案
这就是我在 XML 中的做法,通过这种方式我的图像 height 等于屏幕 width 的 15% :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/favorite"
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:src="@drawable/ic_launcher_background"
app:layout_constraintDimensionRatio="H, 100:15"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>
查看结果:
关于android - 如何在 XML 中指定 View 的宽度和高度的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004436/