【问题标题】:Set view height base on device width in constraintlayout在约束布局中根据设备宽度设置视图高度
【发布时间】:2022-01-21 08:34:16
【问题描述】:

这是我的代码及其输出:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.viewpager2.widget.ViewPager2
    android:layout_width="0dp"
    app:layout_constraintWidth_percent="0.5"
    android:layout_height="0dp"
    app:layout_constraintHeight_percent="0.5"
    android:layout_marginStart="68dp"
    android:layout_marginTop="96dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>

现在 viewpager 宽度是设备宽度的 50%,viewpager 高度是设备高度的 50%,但我想根据设备宽度(设备宽度的 50%)设置 viewpager 高度,可以吗?

【问题讨论】:

    标签: android android-constraintlayout


    【解决方案1】:

    您可以使用 ConstraintLayout 的比率约束属性:

    在布局中添加此行,使其高度等于宽度:

    app:layout_constraintDimensionRatio="1:1"
    

    并删除此行:

    app:layout_constraintHeight_percent="0.5"  //remove this
    

    这将形成一个宽度和高度相等的完美方形视图。

    看看:ConstraintLayout | Ratio

    【讨论】:

      猜你喜欢
      • 2015-08-30
      • 1970-01-01
      • 2014-10-21
      • 2020-01-18
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多