Simon Andersson Simon Andersson - 25 days ago 15
Android Question

Android - Making textview auto resizable text to fit layout

I'm trying to get the size of a text in a textview to use it later in the code.

I have declared a float and my textview as so

private float mStartTextSize;
private TextView mWordTextView;


and then in my onCreate I have

mWordTextView = (TextView) findViewById(R.id.factTextView);
mStartTextSize = mWordTextView.getTextSize();


But as I debug and using my phone, it gets the value of 105 even tho I set it as 30sp in the xml.

<TextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="@string/choose_teams"
android:singleLine="false"
android:id="@+id/wordTextView"
android:textSize="30sp"
android:textColor="@android:color/white"
android:textStyle="bold|italic"
android:layout_below="@+id/titleTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:gravity="top|center"/>

Answer

You are receiving the size in pixel not sp.

getTextSize
float getTextSize ()

Returns
float   the size (in pixels) of the default text size in this TextView.

getTextSize() documentation

you can use this to covert sp/dp to pixel and back without the need of a context.

public static float pxToDp(int px) {
    return px / Resources.getSystem().getDisplayMetrics().density;
}

public static float dpToPx(int dp) {
    return dp * Resources.getSystem().getDisplayMetrics().density;
}
Comments