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.
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:
Get the LayoutParams
of your LinearLayout
.
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!).
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
.)