Search code examples
androidandroid-constraintlayout

how to MODIFY a constraint layout programmatically?


Ive got a view like below :

 <org.rayanmehr.atlas.shared.customview.CustomTextView
    android:id="@+id/tvDownVoteCount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dp"
    app:layout_constraintVertical_bias="0"
    app:layout_constraintTop_toBottomOf="@+id/anchorHelper"
    app:layout_constraintLeft_toRightOf="@+id/tvDownVoteIcon"
    app:layout_constraintBottom_toBottomOf="@+id/imgComment"
    />

how can i modify the value of app:layout_constraintVertical_bias or any other constraint property programmatically without having top set the whole set of the properties again in my activity ?


Solution

  • 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);
    
    //or change the anchor
    constraintSet.connect
    (R.id.tvDownVoteIcon,ConstraintSet.RIGHT,R.id.txt,ConstraintSet.RIGHT,0);
    
    //then apply
    constraintSet.applyTo( (ConstraintLayout) findViewById(R.id.activity_constraint));