how to MODIFY a constraint layout programmatically?

前端 未结 4 787
离开以前
离开以前 2021-02-18 13:56

Ive got a view like below :

 

        
相关标签:
4条回答
  • 2021-02-18 14:35

    I just found the answer in here and you can use ConstraintSet to achieve this like below:

    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(context, R.id.activity_constraint);
    //for example lets change the vertical bias of tvDownVoteIcon
    float biasedValue = 0.2f;
    constraintSet.setVerticalBias(R.id.tvDownVoteIcon, biasedValue);
    //you can do any other modification and then apply
    constraintSet.applyTo( (ConstraintLayout) findViewById(R.id.activity_constraint));
    
    0 讨论(0)
  • 2021-02-18 14:41

    If you are using Kotlin and you have androidx-core-ktx lib you can simply do:

    someView.updateLayoutParams<ConstraintLayout.LayoutParams> { horizontalBias = 0.5f }
    
    0 讨论(0)
  • 2021-02-18 14:47

    Disclaimer: I haven't used this specific functionality. This is just my interpretation on how I would try to do it.

    I think that what you need is ConstraintSet. After obtaining it, you could modify it and apply it again. This is a relevant example from this article.

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        val constraintSet1 = ConstraintSet()
        constraintSet1.clone(constraintLayout)
        val constraintSet2 = ConstraintSet()
        constraintSet2.clone(constraintLayout)
        constraintSet2.centerVertically(R.id.image, 0)
    
        var changed = false
        findViewById(R.id.button).setOnClickListener {
            TransitionManager.beginDelayedTransition(constraintLayout)
            val constraint = if (changed) constraintSet1 else constraintSet2
            constraint.applyTo(constraintLayout)
            changed = !changed
        }
    }
    
    0 讨论(0)
  • 2021-02-18 14:49

    Here is what I did (no need for ConstraintSet, we can work directly on the constraints themselves):

    ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) myView.getLayoutParams();
    params.horizontalBias = 0.2f; // here is one modification for example. modify anything else you want :)
    myView.setLayoutParams(params); // request the view to use the new modified params
    

    it worked like a charm when I had a SeekBar and a TextView below it (aligned to it both left+right), and I wanted to update the TextView position to be under the SeekBar's cursor, so I had to update the horizontal bias params on the SeekBar's OnSeekBarChangeListener

    0 讨论(0)
提交回复
热议问题