Greater Noida, Uttar Pradesh, India
+919990001443
rahul@shuklarahul.co.in

Android square text view with center text

Rahul Shukla

Android square text view with center text

android logo

Android is an awesome OS with great extensibility. And being open source it gives the developers a great leverage to build components on their own. One such need I came through is to have a Square Text View. For a rectangle to be a square, all we need is to keep its width = height. Keeping this simple logic in mind, here’s what I did to make a square text view :

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int max = Math.max(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(max, max);
}
Override onMeasure() method in the new class extended from AppCompatTextView.

Making a TextView square wasn’t challenging. But wait, I noticed the new text view isn’t honouring the “gravity” attribute applied to it. Here’s how it looks like:

android square text view gravity

Android square text view gravity issue

Upon investigating, I observed the TextView seems to be ignoring the gravity attribute upon calling setMeasuredDimensions(). To overcome this issue, I modified the onMeasure method as:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (isSquare) {
            int width = this.getMeasuredWidth();
            int height = this.getMeasuredHeight();
            int size = Math.max(width, height);
            int widthSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
            int heightSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
            super.onMeasure(widthSpec, heightSpec);
        }
    }

And voila, problem solved! The text view widget now displays the centre-aligned text properly. I have used the same method in many of my projects and this is working fine.

You can also visit SO Post for the same and upvote the answer if it helped you. 🙂

 

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: