Center Alignment in Android
I want to know how to center a GUI widge开发者_高级运维t programmatically. Kindly help me. I am using a LinearLayout.
Many Regards.
You need to set gravity for a view as CENTER_HORIZONTAL
with the markup you should use:
android:layout_gravity="center_vertical|center_horizontal"
The difference between android:gravity
and android:layout_gravity
is that android:gravity
positions the contents of that view (i.e. what’s inside the view), whereas android:layout_gravity
positions the view with respect to its parent
In the code you should use:
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Most of the time, you don't have to do this if you defined android:gravity="center"
in the layout file.
You can also perform this by getting the screen size then doing some calculations on it, but this is not recommended.
精彩评论