【问题标题】:Programmatically set margins in a MotionLayout以编程方式在 MotionLayout 中设置边距
【发布时间】:2019-10-19 03:45:35
【问题描述】:

我有一些视图需要以编程方式设置一些边距(来自 applyWindowInsets 侦听器),但视图似乎忽略了我使用代码设置的任何边距,即使我没有为边距设置动画。

我可以很好地设置填充,但我无法仅使用填充来完成我需要的操作。

问题似乎与 MotionLayout 有关,因为如果它是 ConstraintLayout,它可以正常工作。

我一直在用这个util方法。

public static void addTopMargin(View v, int margin) {
    ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin += margin;
}

【问题讨论】:

  • 我一直在使用一种并非在所有情况下都有效的解决方法,但足以让我能够完成我需要的工作。如果你把你想要控制的视图放在一个LinearLayout中,你可以控制子对象上你需要的任何属性,而运动布局将控制LinearLayout上的所有属性

标签: android android-motionlayout


【解决方案1】:

您遇到的问题是 MotionLayout 从分配的 ConstraintSets 派生其边距,因此更改基本边距实际上并没有做任何事情。要使其工作,您需要针对定义MotionScene 的ConstraintSets 之一或两者:

val motionLayout = findViewById(R.id.motionLayoutId)
motionLayout.getConstraintSet(R.id.startingConstraintSet)?
    .setMargin(targetView.id, anchorId, value)

您还可以使用let 对多个视图执行此操作:

val motionLayout = findViewById(R.id.motionLayoutId)
motionLayout.getConstraintSet(R.id.startingConstraintSet)?.let {
    setMargin(firstView.id, anchorId, value)
    setMargin(secondView.id, anchorId, value)
}

对于上边距,使用ConstraintSet.TOP等。

请记住,如果您不想为该边距设置动画,则必须将ConstraintSet 分配给开始和结束。

【讨论】:

    【解决方案2】:

    只需向 UnOrthodox 解决方案添加一个简单的注释,如果您不需要为该边距设置动画,则需要通过添加 ConstraintSets 边距来保持基本边距:

    public static void addTopMargin(View v, int margin) {
        ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin += margin;
        MotionLayout root = findViewById(R.id.motion_layout);
        root.getConstraintSet(R.id.start).setMargin(firstView.id, anchorId, margin);
        root.getConstraintSet(R.id.end).setMargin(firstView.id, anchorId, margin);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-29
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      相关资源
      最近更新 更多