代码之家  ›  专栏  ›  技术社区  ›  Burhanuddin Rashid Abdilahi

以编程方式更改MotionLayout的运动场景中的ConstraintSet属性

  •  0
  • Burhanuddin Rashid Abdilahi  · 技术社区  · 5 年前

    我有一个用例,我想使用MotionLayout创建类似Youtube的动画。中有此动画的示例 this 回购。 但问题是,在这个例子中,他们使用静态高度来启动约束,就像这样 320dp :

    <MotionScene...>
    
        <Transition..>
    
            <OnSwipe... />
    
            <ConstraintSet android:id="@id/start">
    
                <Constraint
                    android:id="@id/top_image_container"
                    android:layout_width="0dp"
                    android:layout_height="320dp"
                    motion:layout_constraintTop_toTopOf="parent"
                    motion:layout_constraintStart_toStartOf="parent"
                    motion:layout_constraintEnd_toEndOf="parent"  />
    
          </ConstraintSet>
      </Transition>
    </MotionScene>
    

    但我的要求是使用纵横比设置约束。对于静态纵横比,我可以使用 app:layout_constraintDimensionRatio="w,16:9" 像这样的约束。

    <Constraint
        android:id="@id/top_image_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        motion:layout_constraintTop_toTopOf="w,16:9"
        motion:layout_constraintTop_toTopOf="parent"
        motion:layout_constraintStart_toStartOf="parent"
        motion:layout_constraintEnd_toEndOf="parent"  />
    

    但每个视频都有一个不同的纵横比,这是我从API得到的。所以我想根据视频设置不同的纵横比。我无法在 ConstraintSet

    我尝试了一种解决方法 android:layout_height="wrap_content" 并以编程方式更改视图纵横比。但它没有工作,动画也没有正常工作。

    如有任何解决方案或建议,将不胜感激。

    0 回复  |  直到 5 年前
        1
  •  13
  •   jossiwolf    5 年前

    您可以访问 ConstraintSet 然后设置比率:

    motionLayout.getConstraintSet(R.id.start)?.let { startConstraintSet ->
        val ratio = imageView.calculateRatio()
        startConstraintSet.setDimensionRatio(R.id.top_image_container, ratio)
        // You can set the width and height here as well
    }