java – Set gravity of a View Programmatically-ThrowExceptions

Exception or error:

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


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

    View clock = mStatusBarView.findViewById(;

    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.

How to solve:

Since extends TextView just cast it to a TextView and set the gravity.

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

Ref: Source code


Have you tried?

clock.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);


Since you cannot use setGravity for a plain View, do something like this,

You can use a RelativeLayout and set a rule like this…

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL|RelativeLayout.CENTER_IN_PARENT, clock.getId());

### clock = (;


try the above code and remove View clock = mStatusBarView.findViewById(;

Leave a Reply

Your email address will not be published. Required fields are marked *