Android change gravity programmatically

Martin Dusek :

I have this layout:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:gravity="left" />

    <TextView
        android:id="@+id/button_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:textSize="40dp" />
</LinearLayout>

Now, I want to modify gravity of the ImageView to left and gravity of the TextView to right. All other values present in xml (width, height, ...) must be preserved.

I tried:

1) setGravity method. Unfortunately, ImageView doesn't have this method. Why?

2)

LinearLayout.LayoutParams iconLayoutParams = new LinearLayout.LayoutParams(icon.getWidth(), icon.getHeight());

iconLayoutParams.gravity = Gravity.LEFT;

This somehow destroys View's dimensions

3)

android.view.ViewGroup.LayoutParams iconLayoutParams = icon.getLayoutParams();

This doesn't have gravity property.

(how is that even possible that icon.setLayoutParams() accepts layout parameters where gravity can be set and icon.getLayoutParams return some different kind of layout params without gravity property? That is a mess)

Can you please help me with that?

Vucko :

I think the easiest way to sort this out is using the 3rd approach but modify it slightly.

LinearLayout.LayoutParams iconLayoutParams = (LinearLayout.LayoutParams) icon.getLayoutParams();

And then do:

iconLayoutParams.gravity = Gravity.LEFT;

Reason LayoutParams itself does not have Gravity is that not all containers have gravity. LinearLayout does, so you need to cast to LinearLayout.LayoutParams since you surely know that your container is LinearLayout. And the method getLayoutParams is in the View class so it must return the parent of all other LayoutParams, which again, does not have to have Gravity.

I hope I explained properly :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=175080&siteId=1