2

I have a XML layout that works just fine on a landscape and portrait orientation with one exception - two buttons inside a LinearLayout need to be placed horizontally on landscape and vertically on portrait device orientation.

I was wondering if there is some easy way to just define a dynamic variable or a string that can be placed in the XML layout file, without having to have to make 2 identical copies of it in layout and layout-land folders.

Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
  • 2
    Consider using re-usable layouts with or directives http://developer.android.com/training/improving-layouts/reusing-layouts.html – Alexander Zhak Sep 22 '14 at 16:27

2 Answers2

3

I ended up doing it programmatically:

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
     // landscape
     linearlayout.setOrientation(LinearLayout.HORIZONTAL); 
} else {
    // portrait  
    linearlayout.setOrientation(LinearLayout.VERTICAL); 
}

Source

Community
  • 1
  • 1
Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
1

Orientation is an enum under the hood with 0 serving as horizontal and 1 serving as vertical. What I did is in res/values/integer.xml I placed a default entry for landscape as 0 and then in res/values-port/integer.xml I placed the same entry but with value 1.

So I have:

/res/values/integer.xml

<resources>
    <item name="linearlayoutOrientation" type="integer">0</item>
</resources>

/res/values-port/integer.xml

<resources>
    <item name="linearlayoutOrientation" type="integer">1</item>
</resources>

And then in my layout file I declare orientation as follows:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="@integer/linearlayoutOrientation">
mtsahakis
  • 793
  • 1
  • 8
  • 18