Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set gravity of a View Programmatically

Tags:

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.

like image 500
user809486 Avatar asked Apr 27 '12 18:04

user809486


People also ask

How do I center a view programmatically in Android?

You can specify the gravity as center_horizontal, center_vertical and center (which centers both horizontally and vertically). On the child views of the LinearLayout you can specify the layout_gravity property, which also supports center_horizontal, center_vertical and center.


2 Answers

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

like image 92
HandlerExploit Avatar answered Sep 18 '22 06:09

HandlerExploit


Have you tried?

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

Edit:

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()); 
like image 45
Arif Nadeem Avatar answered Sep 18 '22 06:09

Arif Nadeem