Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a Custom View on Android?

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>
like image 351
tresnotas Avatar asked Jan 19 '12 19:01

tresnotas


People also ask

How do I center a view in android Studio?

To center a view, just drag the handles to all four sides of the parent.

How do you center on android?

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.

How do you center a view in linear layout?

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

How do I center an object in android Studio?

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.


1 Answers

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.

like image 159
Oderik Avatar answered Oct 26 '22 21:10

Oderik