Removing/Editing a constraint of a view inside a ConstraintLayout programmatically

4.6k views Asked by At

I have a view (Linearlayout) inside a ConstraintLayout with the following attributes:

 android:id="@+id/myView"
 app:layout_constraintTop_toBottomOf="@+id/anotherView"
 app:layout_constraintLeft_toLeftOf="parent"
 app:layout_constraintRight_toRightOf="parent"

At some occasions I wish to align myView to the left, by simply removing the right constraint. however I'm not able to do so.
I tried to use the following, simply to copy and apply the constraint parameters:

 ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(holder.myView.getLayoutParams());
 holder.myView.setLayoutParams(layoutParams);

but the layoutParams always receives an empty parameters set,and sends the view to the top left corner. Perhaps it's because I'm using this inside of a recyclerView?

How it looks inside the recyclerView:

public void onBindViewHolder(final RecyclerView.ViewHolder basicHolder, int position) {
ProfileAdapter.UserInfoViewHolder holder = (ProfileAdapter.UserInfoViewHolder) basicHolder;
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(holder.myView.getLayoutParams(‌​));
holder.myView.setLayoutParams(layoutParams); 
}
2

There are 2 answers

0
Nicolas Roard On BEST ANSWER

There's a bug (will be fixed in the next release) when setting layout params the way you do it. In the meantime, you can do:

ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) holder.myView.getLayoutParams();
layoutParams.rightToRight = ConstraintLayout.LayoutParams.UNSET;
holder.myView.setLayoutParams(layoutParams);
0
CoolMind On

The same in Kotlin:

val layoutParams = view.layoutParams as ConstraintLayout.LayoutParams
layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.UNSET