代码之家  ›  专栏  ›  技术社区  ›  Adam

使用合并从布局创建constraintset

  •  0
  • Adam  · 技术社区  · 6 年前

    我想做一个 Changebounds()

    通常,我通过创建两个约束集来完成此操作:

    private val originalState = ConstraintSet().apply {
        clone(context, R.layout.layout_meta_syntactic)
    }
    
    private val expandedState = ConstraintSet().apply {
        clone(context, R.layout.layout_meta_syntactic)
        // Change some constraints
        connect(
            R.id.button, ConstraintSet.END,
            R.id.foo_text, ConstraintSet.START
        )
    }
    

    并用以下动画来回播放:

    TransitionManager.beginDelayedTransition(id_of_my_component_in_fragment, transition)
    originalState.applyTo(id_of_my_component_in_fragment)
    

    但现在我被一个 <merge>

    复合成分:

    class MyCompoundView : ConstraintLayout {
    
    // Omissions
    inflate(context, R.layout.layout_meta_syntactic, this)
    

    <merge xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/some_id"
        tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout">
    
        // Views 
    

    当试图将布局克隆到以编程方式设置的约束时,我得到:

     Caused by: android.view.InflateException: Binary XML file line #2: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true
     Caused by: android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true
    

    如何从这样的布局创建约束集?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Pawel    6 年前

    你有两个选择:

    1. ConstraintLayout 保存布局引用的根 include 标签。
    2. 从自定义视图的新实例克隆布局参数: ConstraintSet.clone(context, MyCompoundView(context)) .

    ConstraintSet.clone(context, layoutRes) 实际上是很粗糙的( source 约束布局 在解析要生成的布局参数之前,从提供的布局文件(包括所有子视图)中 ConstraintSet .

        2
  •  0
  •   Adam    6 年前

    解决方案是克隆复合组件,它是一个ConstraintLayout

    class MyCompoundView : ConstraintLayout {
    
        // make sure to clone after inflating the layout to the component
    
        originalState = ConstraintSet().apply {
            clone(this@MyCompoundView)
        }
    
        expandedState = ConstraintSet().apply {
            clone(this@MyCompoundView)
            // Change some constraints
             connect(
                 R.id.button, ConstraintSet.END,
                 R.id.foo_text, ConstraintSet.START
            )
        }
    }