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?
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 waswrap_content
, the TextView will be place in the right side of your LinearLayout.