Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal LinearLayout with children ordered right-to-left?

I have a horizontal LinearLayout that's programmatically filled with its children. I would like to be able to switch to a right-to-left layout (i.e. child 0 is on the far right, child 1 to its left, etc.) . The thing is, I want the layout to switch from RtL to LtR and back dynamically, that's why e.g. this question is irrelevant to my case.

There doesn't seem to be any way to set it directly in the code, especially since gravity is for alignment, not ordering.

So far I see the following workarounds:

  • On the ordering switch, re-add the children in an inverted order (problem: very ugly and resource-consuming).
  • Implement a subclass of LinearLayout with an overridden onLayout() method (problem: lots of copy-pasting the Android source due to helper layout members having a restrictive visibility).
  • Replace the LinearLayout with another, e.g. a TableLayout or a RelativeLayout, and change the layout params of the children on switch (problem: still somewhat kludgey).

Any more direct solutions or better workarounds?

EDIT: to clarify, I'm creating the children practically once during the activity run-time, and I can store them in a helper array/collection at no complication to the code.

like image 848
mikołak Avatar asked Sep 05 '25 00:09

mikołak


2 Answers

While re-creating the children might be resource-intensive, re-ordering shouldn't be that bad. You can take the existing views using getChildAt and getChildCount and then put them back in using the addView override with an index.

like image 143
kabuko Avatar answered Sep 07 '25 14:09

kabuko


Do a LinearLayout.setRotationY(180). You will also have to set the Y rotation of the child views of the Linear Layout to 180 also. So for example:

private void horizontal() {
    LinearLayout layout = (LinearLayout) v.findViewById(R.id.layout);
    View childView1 = (View) v.findViewById(R.id.childView1);
    View childView2 = (View) v.findViewById(R.id.childView2);

    layout.setRotationY(180);
    childView1.setRotationY(180);
    childView2.setRotationY(180);
}

The code may be wrong, but you get the idea.

like image 27
Andy Avatar answered Sep 07 '25 15:09

Andy