Im trying to copy RelativeLayout.LayoutParams, and i need the new Params to be exactly like the old ones. So consider this method:
private RelativeLayout.LayoutParams copyParams(RelativeLayout.LayoutParams source){
RelativeLayout.LayoutParams copy = new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams)source);
return copy;
}
Now, this works all right, but it will only compile above API-Level 19, as eclipse conveniently tells me.
To make this work pre-API-19, i tried this:
private RelativeLayout.LayoutParams copyParams(RelativeLayout.LayoutParams source){
RelativeLayout.LayoutParams copy = new RelativeLayout.LayoutParams((ViewGroup.LayoutParams)source);
copy.setMargins(source.leftMargin, source.topMargin, source.rightMargin, source.bottomMargin);
return copy;
}
By casting to ViewGroup.LayoutParams, i can force the use of the ViewGroup.LayoutParams CopyConstructor. It is readily available, but it will only copy the height and width. So i need to transfer the margins myself, which i do in line 3 of example 2. But this still leaves out the rules in the source layout, like RelativeLayout.BELOW, for example.
I can't find a copyRules() or setRules() method (or anything equivalent) anywhere in the docs, but i can see the addRule() method of RelativeLayout.LayoutParams. Considering that source.getRules() returns an Array i think i could loop over that and add each rule to my new LayoutParams, but that feels like im doing it wrong. Is there a sane way to copy these rules?
TL;DR: Before API 19, is there a way to copy the rules of RelativeLayout.LayoutParams wholesale, and if not, what is the least insane way to copy them at all?
well, if clone didn't work, probably your last resort will be a good ol' fashioned for-loop uh.
use getRules() to get the list of rules in the current LayoutParams and addRule(int, int) to add them to a new LayoutParam.
old answer:
In this case I would try .clone.
LayoutParams in general are very simple objects with just a few integers, so .clone should handle it nicely.
original answer:
try:
RelativeLayout.LayoutParams copy = new RelativeLayout.LayoutParams((ViewGroup.LayoutParams)source);
the constructor with ViewGroup.LayoutParams exist since API 1.
ps.: Even thou I know it will compile, I strongly suggest you to double check that all the parameters were properly copied over (not just with, height n margins)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With