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

相关推荐
莞凰8 小时前
昇腾CANN的“灵脉根基“:Runtime仓库探秘
android·人工智能·transformer
NiceCloud喜云9 小时前
Claude Files API 深入:从上传、复用到配额管理的工程化指南
android·java·数据库·人工智能·python·json·飞书
ujainu9 小时前
CANN pto-isa:虚拟指令集如何连接编译与执行
android·ascend
赏金术士10 小时前
第六章:UI组件与Material3主题
android·ui·kotlin·compose
TechMerger11 小时前
Android 17 重磅重构!服役 20 年的 MessageQueue 迎来无锁改造,卡顿大幅优化!
android·性能优化
yuhuofei202114 小时前
【Python入门】Python中字符串相关拓展
android·java·python
dalancon14 小时前
Android Input Spy Window
android
dalancon16 小时前
InputDispatcher派发事件,查找目标窗口
android
我命由我1234516 小时前
Android Framework P3 - MediaServer 进程、认识 ServiceManager 进程
android·c语言·开发语言·c++·visualstudio·visual studio·android runtime
天才少年曾牛17 小时前
Android14 新增系统服务后,应用调用出现 “hidden api” 警告的原因与解决方案
android·frameworks