Search code examples
androidxmlandroid-linearlayoutlayout-gravity

How can I remove effect of gravity using LayoutParams method in Android? (Gravity.NO_GRAVITY doesn't work.)


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);

Solution

  • 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