-2

I have expected that TextView was aligned to the right because of NO_GRAVITY, however it was aligned to the left. Shouldn't NO_GRAVITY leave the gravity setting as it is, instead of aligning it to the left. If I also remove this two lines belove, it still aligns the TextView to the left even if I specify android:layout_gravity="center" in xml code.

params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;

How can I change other properties of the layout without effecting its gravity? What is exactly the difference between LEFT and NO_GRAVITY?

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.gravity = Gravity.NO_GRAVITY;
textView.setLayoutParams(params);
  • Left forces left, while no gravity defaults the gravity to nothing. meaning left – Zoe Jun 06 '17 at 18:40

1 Answers1

0

Gravity.NO_GRAVITY might (its just a guess) mean "default" gravity, which in your locale is left, but in some countries it might be right (arabic e.g., due to writting direction). if you want centered aligning then you can set Gravity.CENTER, obviusly...

if you want to combine two Gravities, then you can use flag add

params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;

besides that if you are setting LinearLayout.LayoutParams then textViews parent must be LinearLayout. in rare cases with dynamic layouts and multiple threads change in params shoud be continued with requestLayout() method call for forcing "redraw" in proper position and thread

snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • I've changed layout **Orientation** to **horizontal** and changed `Gravity.RIGHT` to `Gravity.BOTTOM` in the code but still it is the same(aligned to top left). I know the difference between layout_gravity and gravity. Also i.e. I am trying to set the whole TextView's alignment to right. My expectation had been that there wouldn't be any change on the gravity of the TextView after `NO_GRAVITY` was executed. My purpose is changing other properties of the layout without effecting its gravity as I said – İsa Yurdagül Jun 06 '17 at 19:40
  • show then XML and/or code for inflating. are you shure that `textView`s parent is `LinearLayout`? can you show its attributes? – snachmsm Jun 06 '17 at 21:00
  • nothing suspicious here... you may try with `requestLayout()` call just after `setLayoutParams`. you didn't show Java code and place where you are changing these `LayoutParam`a, it may be the key – snachmsm Jun 07 '17 at 08:35