I am trying to center the view for different resolutions using the layout, and gravity properties, but it's not working. Is there a way to make the custom view center horizontally across different resolutions?
Do I need to do something on the onMeasure method ?
Here is one of the things I am trying right now, the view is to the left of the center..
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:gravity="center_horizontal">
<com.application.app.ui.CustomView
android:id="@+id/ivCoinAnimation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
</FrameLayout>
To center a view, just drag the handles to all four sides of the parent.
android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.
The LinearLayout has a gravity property which supports centering it's child views. You can specify the gravity as center_horizontal, center_vertical and center (which centers both horizontally and vertically).
You can use RelativeLayout with nested LinearLayout . Put all your view into LinearLayout without applying centering and set centerInParent="true" . But in your case just remove layout_gravity attribute from your views and add gravity="center" to the root view.
Assuming you have a View
inside a layout like FrameLayout
, you would set View
's layout_gravity
to center
. Don't mix it up with gravity
!
Also, it may indeed be necessary to override onMeasure(). Read it's documentation to decide if you need to override it. If you do, be aware that the parameters are encoded with View.MeasureSpec
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With