简体   繁体   中英

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 (ie 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 eg 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, eg 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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM