Reputation: 5089
I have a TextView that is right aligned in a list item. Its background is a drawable, which is just an oval. This textview serves as a badge, and it needs to be a circle (equal width and height).
I achieve this by running the following code:
textView.setText(badgeCount);
textView.measure(0, 0);
ViewGroup.LayoutParams params = textView.getLayoutParams();
int size = Math.max(textView.getMeasuredWidth(), textView.getMeasuredHeight());
params.width = size;
params.height = size;
badgesCountTextView.setLayoutParams(params);
This works except the text is left aligned. My xml looks like this:
<RelativeLayout>
...
<TextView
android:id="@+id/badge_count_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:textSize="15sp"
android:textColor="@color/white"
android:layout_alignParentRight="true"
android:background="@drawable/black_circle"
tools:text="45"
android:gravity="center"/>
</RelativeLayout>
How am I supposed to center the text within my badge view? I cannot set a fixed width or height, because that needs to be set dynamically depending on the text size. Can anyone point me in the right direction?
Upvotes: 0
Views: 1034
Reputation: 93726
You've set the textview size to wrap content in width and height. That means the view is extremely small- just the size of the text. So it is centered. What you probably want is to either set its width to fill_parent, or to set its layout_leftAlign and rightAlign or toLeftOf and toRightOf such that it ends up with a larger size. But without knowing the rest of your layout and what you want it to look like we can't help you.
Upvotes: 0
Reputation: 2985
Change the layout_width
and layout_height
of the TextView to fill_parent
and set the gravity of the TextView to center
like this:
<RelativeLayout>
...
<TextView
android:id="@+id/badge_count_text_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:textSize="15sp"
android:textColor="@color/white"
android:layout_alignParentRight="true"
android:background="@drawable/black_circle"
tools:text="45"
android:gravity="center"/>
</RelativeLayout>
otherwise, if your TextView is as small as your text, you could not center it easily
Upvotes: 2