Android LinearLayout set layout_gravity in java code

e-info128 picture e-info128 · Feb 6, 2013 · Viewed 15.1k times · Source

I have a problem on this layout :(

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cuerpo"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="vertical" >
...

In java code

LinearLayout cuerpo = (LinearLayout) findViewById(R.id.cuerpo);

if(align){
   cuerpo.setGravity(Gravity.CENTER_VERTICAL);
}else{
   cuerpo.setGravity(Gravity.NO_GRAVITY);
}

I need layout_gravity to be no gravity.

Answer

btalb picture btalb · Feb 6, 2013

The layout gravity you are talking about is within the LayoutParams of of the LinearLayout object. So, logically, to get this you have to follow the following steps:

  1. Get the LayoutParams of your LinearLayout.

  2. If you know what the LayoutParams are supposed to be, you can cast them (beware, this is based on your choice, so you must make sure it is correct!).

  3. Set the gravity of the LayoutParams as you desire.

So in code this would be:

ViewGroup.LayoutParams layoutParams = cuerpo.getLayoutParams(); // Step 1.
LinearLayout.LayoutParams castLayoutParams = (LinearLayout.LayoutParams) layoutParams; // Step 2.
castLayoutParams.gravity = Gravity.CENTER_VERTICAL; // Step 3.

Or as a simple one liner that does all steps in one:

((LinearLayout.LayoutParams) cuerpo.getLayoutParams()).gravity = Gravity.CENTER_VERTICAL;

Please beware:

I cannot see exactly what you are trying to do, but it does not seem correct. The type of LayoutParams is not the type of the View, but the type of Layout that your View is to reside in.

(i.e. like in @gincsait's reference, if I have a Button in a LinearLayout, then the LayoutParams of the Button will be of type LinearLayout.LayoutParams. The same cannot be said for the LayoutParams of the LinearLayout.)