当前位置:   article > 正文

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

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

修改约束比例:

  1. /// 约束比例修改
  2. private fun adapterCellRatio(holder: BaseViewHolder) {
  3. // 确保视图完全加载后进行操作
  4. val consLayoutBaseBG = holder.getView<ConstraintLayout>(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. <?xml version="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。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号