gpt4 book ai didi

android - 如何在 XML 中指定 View 的宽度和高度的百分比?

转载 作者:行者123 更新时间:2023-11-30 00:05:59 26 4
gpt4 key购买 nike

是否可以在 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>

查看结果:

Result

关于android - 如何在 XML 中指定 View 的宽度和高度的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com