[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。

相关推荐
好的佩奇6 小时前
蓝牙之设备角色与连接
android·flutter·蓝牙
雨白14 小时前
Android 消息机制剖析:从 Handler 投递到 Looper 循环的全链路
android
GY-9315 小时前
【Android】数据分层和依赖注入
android
传奇开心果编程16 小时前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
星空孤辰17 小时前
【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理
android·windows
恋猫de小郭18 小时前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
思想觉悟19 小时前
Android启动流程之点rc文件
android·linux·面试
_祝你今天愉快1 天前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋1 天前
Android 工程师的技术信仰崩塌史
android
AirDroid_cn1 天前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android