I get the LayoutParams for my view and then I change the margins and call setLayoutParams(). After the call, the margins in the LayoutParams are set back to what they were in the XML that defined the views. I tried to use the LayoutParams and modify them. I also tried to create a new object and use that. In either case, the margins do not "stick" and get reset to their original values; the view on the screen matches what I see in the data.
I tried it this way, just modifying the existing params:
ConstraintLayout.LayoutParams p = (ConstraintLayout.LayoutParams) v.getLayoutParams();
p.setMargins( left, top, right, bottom );
v.setLayoutParams( p );
I also tried to create new params:
ConstraintLayout.LayoutParams p = (ConstraintLayout.LayoutParams) v.getLayoutParams();
ConstraintLayout.LayoutParams derp = new ConstraintLayout.LayoutParams( p );
derp.setMargins( left, top, right, bottom );
v.setLayoutParams( derp );
In the debugger, I can check that the margins I set are actually set in the params object. I look at those same values right after the call to setLayoutParams() and they are set to the values I have in the XML that contains this view.
I didn't seem to have this trouble when using LinearLayout. This seems to happen only for ConstraintLayout. There must be a way to change the margins - I realy don't want to have to have two almost identical XML files just to have two different sets of margins for one view within a fairly complicated custom view.
I looked at dozens of S.O. questions and answers about Android LayoutParams and none of the information helped. No variation of the code works in my case.
[edit]
I also tried to use ViewGroup.MarginLayoutParams to see if that changed the behavior. It had no effect and the margins in that object also get set back to their original value after the call to setlayoutParams().