Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the direction of a LinearLayout

How can I reverse the direction of a linear layout?

for example, if my layout is [view1, view2, view3] I want to create [view3, view2, view1]. My goal is to inflate a left and a right handed instances from one XML layout.

like image 488
ZeroEric Avatar asked Dec 16 '12 17:12

ZeroEric


People also ask

What is the default orientation of a LinearLayout?

Linear Layout You can specify whether that line is horizontal or vertical by using the android:orientation attribute. By default, orientation is horizontal. Horizontal orientation will only have one single row of elements on the screen and in the case of vertical orientation, it will only have one child per row.

What is the difference between RelativeLayout and LinearLayout?

LinearLayout : is a ViewGroup that aligns all children in a single direction, vertically or horizontally. RelativeLayout : is a ViewGroup that displays child views in relative positions. AbsoluteLayout : allows us to specify the exact location of the child views and widgets.

What is layout_weight and weightSum in android?

android:weightSum. Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

What is android layout_weight?

In a nutshell, layout_weight specifies how much of the extra space in the layout to be allocated to the View. LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view.


2 Answers

Generally I would say you cannot do this using the standard SDK. You could however create a method which gets all of the subviews out of the LinearLayout, removes them from the LinearLayout, and then adds them back in reverse order.

LinearLayout ll = // inflate
ArrayList<View> views = new ArrayList<View>();
for(int x = 0; x < ll.getChildCount(); x++) {
    views.add(ll.getChildAt(x));
}
ll.removeAllViews();
for(int x = views.size() - 1; x >= 0; x--) {
    ll.addView(views.get(x));
}
like image 188
mtmurdock Avatar answered Nov 19 '22 04:11

mtmurdock


Just add the following code to LinearLayout:

android:layoutDirection="rtl"

But it permanently reverses the order - not just for RTL locales :(

like image 43
Dmitry Avatar answered Nov 19 '22 02:11

Dmitry