Custom android square textview text is not centered
<p>I am trying to create a textview that will always be squared so I have implemented this custom class.</p>

<pre><code>public class SquareTextView extends TextView {

    public SquareTextView(Context context) {
        super(context);
    }

    public SquareTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int max = Math.max(getMeasuredWidth(), getMeasuredHeight());
        setMeasuredDimension(max, max);
    }

}
</code></pre>

<p>Here is an example layout that illustrates the problem:</p>

<pre><code>&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"&gt;


    &lt;com.mypackage.SquareTextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_gravity="right|top"
        android:background="#000"
        android:gravity="center"
        android:padding="4dp"
        android:text="1"
        android:textColor="#FFF"/&gt;

&lt;/LinearLayout&gt;
</code></pre>

<p>Here is an image of this</p>

<p><a href="https://i.stack.imgur.com/cauEP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cauEP.png" alt="enter image description here"></a></p>

<p>This works great in getting the view squared, however, it seems like the gravity gets messed up. With this, the text seems to always be in the top left corner. How can I have a TextView that will always be squared but still keep the gravity or at least be able to center the text?</p>

<p><strong>EDIT:</strong> After some testing I have noticed that if you set the width or height to a specific dp size the gravity seems to be working again. So it probably has to do with the <code>WRAP_CONTENT</code> attribute. Will that be handled in another way in the onmeasure method that could cause my own method to not work as expected?</p>