Skip to content Skip to sidebar Skip to footer

Is There A Way To Copy Constraint Parameters Of A Component In ConstraintLayout?

I have a View in my ConstraintLayout which is positioned in XML. Then I want to change this view to another view on button click. I have the script to do it and it works OK, but th

Solution 1:

You can do this by re-using the original view's ConstraintLayout.LayoutParams object:

button.setOnClickListener(v -> {
    ConstraintLayout.LayoutParams params = 
            (ConstraintLayout.LayoutParams) viewToRemove.getLayoutParams();

    parent.removeView(viewToRemove);
    parent.addView(viewToAdd, params);
});

Note that this will give the same width and height as the old view as well, so you may have to explicitly set those if you need them to be different:

ConstraintLayout.LayoutParams params = 
        (ConstraintLayout.LayoutParams) toRemove.getLayoutParams();

params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

Post a Comment for "Is There A Way To Copy Constraint Parameters Of A Component In ConstraintLayout?"