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


    修改约束比例:

    1. /// 约束比例修改
    2. private fun adapterCellRatio(holder: BaseViewHolder) {
    3. // 确保视图完全加载后进行操作
    4. val consLayoutBaseBG = holder.getView(R.id.cl_cell_bg)
    5. // 获取当前约束比例
    6. val currentDimensionRatio = getCurrentDimensionRatio(consLayoutBaseBG, R.id.cl_cell_bg_id)
    7. val targetDimensionRatio = "h,78:65"
    8. if (currentDimensionRatio != targetDimensionRatio) {
    9. val constraintSet = ConstraintSet() // 创建 ConstraintSet 实例
    10. constraintSet.clone(consLayoutBaseBG) // 加载当前布局约束
    11. constraintSet.setDimensionRatio(R.id.cl_cell_bg_id, targetDimensionRatio ) // 修改 layout_constraintDimensionRatio 的比例
    12. constraintSet.applyTo(consLayoutBaseBG) // 应用新的约束
    13. }
    14. }
    1. "1.0" encoding="utf-8"?>
    2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:id="@+id/cl_cell_bg"
    6. android:layout_width="match_parent"
    7. android:layout_height="wrap_content"
    8. android:background="@color/black"
    9. android:radius="10dp">
    10. <androidx.constraintlayout.widget.ConstraintLayout
    11. android:id="@+id/cl_cell_bg_id"
    12. android:layout_width="match_parent"
    13. android:layout_height="0dp"
    14. app:layout_constraintBottom_toBottomOf="parent"
    15. app:layout_constraintDimensionRatio="h,78:60"
    16. app:layout_constraintLeft_toLeftOf="parent"
    17. app:layout_constraintRight_toRightOf="parent"
    18. app:layout_constraintTop_toTopOf="parent">
    19. <androidx.constraintlayout.widget.ConstraintLayout
    20. android:id="@+id/cl_center"
    21. android:layout_width="match_parent"
    22. android:layout_height="match_parent">
    23. androidx.constraintlayout.widget.ConstraintLayout>
    24. androidx.constraintlayout.widget.ConstraintLayout>
    25. androidx.constraintlayout.widget.ConstraintLayout>

    注意报错

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

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

  • 相关阅读:
    Redo Log Undo Log 与 Bin Log介绍
    视频号视频怎么保存?教你三种方法
    食品饮料行业渠道商管理系统解决方案:实现渠道数字化营销布局
    HashMap存值、取值及哈希碰撞原理分析
    Java高手的30k之路|面试宝典|精通JVM(二)
    数据文件采用错误方式删除后的解决办法
    【springboot】11、自定义转换器
    在Vue中如何渲染使用Vue写法的HTML文件?
    网络工程师的网络安全之路:应对威胁与保障数据
    string类的常用方法
  • 原文地址:https://blog.csdn.net/u012881779/article/details/139939475