Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing the constraint of a view in ConstraintLayout

I am trying to change the left constraint (guideline) of a view inside my ConstraintLayout on press of a button. My layout XML (relevant parts) looks like this:

<ProgressBar
  android:id="@+id/progress_bar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="0dp"
  android:layout_marginRight="8dp"
  android:layout_marginTop="8dp"
  android:indeterminate="true"
  android:visibility="gone"
  app:layout_constraintBottom_toTopOf="@+id/guideline_bcrumbs_bottom"
  app:layout_constraintHorizontal_bias="0.0"
  app:layout_constraintLeft_toLeftOf="@+id/guideline_group_left"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_group_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.2"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="205dp"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_category_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.45"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="461dp"/>

Here, I want to change the progress bar's constraintLeft_toLeftOf property from guideline_group_left to guideline_category_left dynamically. Is there a way to achieve this?

EDIT:

I have added the following lines to adjust the constraint (based on this link: http://www.techotopia.com/index.php/Managing_Constraints_using_ConstraintSet)

ConstraintSet set = new ConstraintSet();
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);

However, after these changes, the progress bar does not show up at all. I feel like I am close, but am probably missing something.

EDIT 2

I realized I forgot to add the following line, which is why it did not work.

set.clone(mConstraintLayout);
like image 509
epekel Avatar asked Feb 05 '23 07:02

epekel


1 Answers

SOLUTION:

I managed to solve my issue with the following lines of code, it might help someone else if they face a similar problem.

ConstraintSet set = new ConstraintSet();
set.clone(mConstraintLayout);
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);
like image 84
epekel Avatar answered Feb 07 '23 12:02

epekel