0

If you want to set the gravity of a View like LinearLayout programmatically, you have 2 ways:

1)

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.FILL_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);

params.gravity = Gravity.RIGHT;
MyLinearLayout.setLayoutParams(params);

2)

MyLinearLayout.setGravity(Gravity.RIGHT);

What is difference between these 2 ways?

Bob
  • 22,810
  • 38
  • 143
  • 225
  • 1
    possible duplicate of [Android - gravity and layout\_gravity](http://stackoverflow.com/questions/3482742/android-gravity-and-layout-gravity) – user Jan 13 '14 at 07:32
  • @Luksprog No it is not duplicate. Because that answer is not about setting the gravity in code. The main problem in this question is setting the gravity in code! – Bob Jan 13 '14 at 07:33
  • Your question doesn't add any real value. The documentation clearly states what you basically said in your answer, so it's kind of pointless. – user Jan 13 '14 at 07:41
  • @Luksprog That was my question. I searched and found that answer. But it could not help me. Because there was no explanation about `LayoutParams` and `setGravity(...)` And finally I found it myself. – Bob Jan 13 '14 at 07:44

1 Answers1

2

It is important you know the difference.

In the first way you are setting that layout gravity of your LinearLayout. It means you are setting the position of your layout in its parent View. It is equivalent to android:layout_gravity="right" in xml layouts.

But in the second way you are setting the position of child views in your Linearlayout and it is equivalent to android:gravity="right" in xml layouts. For example if you put a TextView in your LinearLayout and its width was wrap_content, the TextView will be place in the right side of your LinearLayout.

Bob
  • 22,810
  • 38
  • 143
  • 225