[Android]修改XML中定义的约束比例

修改约束比例:

Kotlin 复制代码
/// 约束比例修改
private fun adapterCellRatio(holder: BaseViewHolder) {
    // 确保视图完全加载后进行操作
    val consLayoutBaseBG = holder.getView<ConstraintLayout>(R.id.cl_cell_bg) 
    // 获取当前约束比例
    val currentDimensionRatio = getCurrentDimensionRatio(consLayoutBaseBG, R.id.cl_cell_bg_id)
    val targetDimensionRatio = "h,78:65"
    if (currentDimensionRatio != targetDimensionRatio) {
        val constraintSet = ConstraintSet() // 创建 ConstraintSet 实例
        constraintSet.clone(consLayoutBaseBG) // 加载当前布局约束
        constraintSet.setDimensionRatio(R.id.cl_cell_bg_id, targetDimensionRatio ) // 修改 layout_constraintDimensionRatio 的比例
        constraintSet.applyTo(consLayoutBaseBG) // 应用新的约束
    }
}
XML 复制代码
<?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:id="@+id/cl_cell_bg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black"
    android:radius="10dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/cl_cell_bg_id"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="h,78:60"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/cl_center"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

注意报错

Error updating constraint: All children of ConstraintLayout must have ids to use ConstraintSet

报错信息指出,ConstraintLayout 中的所有子视图都必须有 ID 才能使用 ConstraintSet。这是因为 ConstraintSet 需要通过视图的 ID 来引用和修改约束。你需要确保所有直接或间接属于 ConstraintLayout 的子视图都有一个唯一的 ID。

相关推荐
_小马快跑_1 小时前
Android | 利用ItemDecoration绘制RecyclerView分割线
android
_小马快跑_2 小时前
别再手写 if/else 判断了!赶紧来掌握 Kotlin 的 coerce 三兄弟吧
android
_小马快跑_2 小时前
Android Xfermode应用:实现圆角矩形、圆形等图片裁切
android
怀旧,2 小时前
【数据结构】4.单链表实现通讯录
android·服务器·数据结构
yechaoa2 小时前
Widget开发实践指南
android·前端
顾林海4 小时前
Flutter 图标和按钮组件
android·开发语言·前端·flutter·面试
匹马夕阳5 小时前
(二十二)安卓开发中的数据存储之SQLite简单使用
android·数据库·sqlite
_一条咸鱼_5 小时前
大厂Android面试秘籍:上下文管理模块
android·面试·android jetpack
mingzhi615 小时前
绿盟二面面试题
android·web安全·渗透测试
SY.ZHOU8 小时前
Flutter 与原生通信
android·flutter·ios