Solution 1 :
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 🙂
Problem :
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?