Layout orientation in code

AndroidOrientationAndroid Linearlayout

Android Problem Overview


I have this code in my application:

LinearLayout.LayoutParams params =
    new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);

and I just want to set the orientation of the LinearLayout to vertical. The equivalent in XML is:

android:orientation="vertical"

How can I do it in the code, without XML?

Android Solutions


Solution 1 - Android

You can't change LinearLayout's orientation using its LayoutParams. It can be done only with a LinearLayout object.

LinearLayout layout = /* ... */;
layout.setOrientation(LinearLayout.VERTICAL);

Solution 2 - Android

You can use like this one:

LinearLayout myll = (LinearLayout) findViewById(R.id.yourLinearLayout);
myll.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
myll.setOrientation(LinearLayout.VERTICAL);

Solution 3 - Android

You need to instance LinearLayout. After that you can call setOrientation()

LinearLayout myLayout = ...;
myLayout.setLayoutParams(new LayoutParams(LinearLayout.WRAP_CONTENT, LinearLayout.WRAP_CONTENT);
myLayout.setOrientation(LinearLayout.VERTICAL);

That should do the job :)

For more infos check the Android API.

Solution 4 - Android

A working sample below (it's LayoutParams.WRAP_CONTENT, NOT LinearLayout.WRAP_CONTENT)

myLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
myLayout.setLayoutParams(layoutParams);

Solution 5 - Android

In case anyone else arrives here like me looking for the answer for Xamarin, the equivalent is:

LinearLayout layout = /* ... */;
layout.Orientation = Orientation.Vertical;
layout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent);

Solution 6 - Android

Simply use as follow :-

LinearLayout mlayout = new LinearLayout(context);
mlayout.setOrientation(2);

2 means Vertical, 1 is used for horizontal.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregView Question on Stackoverflow
Solution 1 - AndroidMichaelView Answer on Stackoverflow
Solution 2 - AndroidBalaji KhadakeView Answer on Stackoverflow
Solution 3 - AndroiddudeldidadumView Answer on Stackoverflow
Solution 4 - AndroidTiaView Answer on Stackoverflow
Solution 5 - AndroidstovrozView Answer on Stackoverflow
Solution 6 - AndroidYama RaahiView Answer on Stackoverflow