Set gravity of a View Programmatically

user809486 picture user809486 · Apr 27, 2012 · Viewed 46.6k times · Source

Im working on a View over Android Source Code. I was wondering how can we setup multiple gravities, to a custom View

This is the XML

<com.android.systemui.statusbar.policy.Clock
        android:id="@+id/clock"
        android:textAppearance="@style/TextAppearance.StatusBar.Clock"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:singleLine="true"
        android:paddingLeft="6dip"
        android:gravity="center_vertical|left"
        />

As you see, default gravity is center_vertical|left, so my Java code should be something like this

    View clock = mStatusBarView.findViewById(R.id.clock);

    if (clock != null) {
        SOMEHOW SET GRAVITY -> mCenterClock ? Gravity.CENTER : (Gravity.CENTER_VERTICAL | Gravity.LEFT);
    }

setGravity method don't work on View. So is there an alternative of setting gravity without losing the width and height by default?.

Thanks in advance.

Answer

HandlerExploit picture HandlerExploit · Apr 27, 2012

Since com.android.systemui.statusbar.policy.Clock extends TextView just cast it to a TextView and set the gravity.

 TextView clock = (TextView) mStatusBarView.findViewById(R.id.clock);
 clock.setGravity(mCenterClock ? Gravity.CENTER : (Gravity.CENTER_VERTICAL | Gravity.LEFT));

Ref: Source code