For example I'll use Button element, with layout params such margins and alignment. Depend on the run logic this Button can be in 1 of 2 states:
<!--State 1: Right orientation-->
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"/>
<!--State 2: Left orientation-->
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"/>
- Trivial Implementation: Put them both on the
view
and control viaView.Visibility
. - Programmatic Implementation:
//change to right orientation - state 1
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)myButton.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0); //instead of remove rule which needs api>17...
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
myButton.setLayoutParams(params);
ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams)myButton.getLayoutParams();
marginParams.setMargins(0, 0, 5, 0); //(left, top, right, bottom)
myButton.requestLayout();
The problem: Too much code, and the setMargins(l,t,r,b)
is on pixels and not dp
- It's a bug... EDIT: There is a solution for this.
I wonder if there are implementations using dynamic attach of custom layouts to only 1 code object of Button
? Is it possible/logic here to use selector
here?
EDIT- What I'm looking for is something like:
In activity xml there is a button view whom layout params set on some other xml and non "inline". And the button view has this xml as source for it's layout params. However this button has 2 states of layouts (left/right...) and it depends on some logic (not android: ... e.g. state_pressed, some code flow situation). And when this happens, I want to switch layouts. Better if it will be 1 extra xml with selector.
Thanks,