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?


Solution 1:

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:

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:

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:

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);