63

I need the current TextSize of the TextView in sp units.

But getTextSize() returns the size in pixels. So is there a way to convert pixels to sp?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Nital
  • 975
  • 3
  • 9
  • 15
  • 1
    See also [this answer](http://stackoverflow.com/a/42108115/3681880) for `DP -> PX`, `PX -> DP`, `SP to PX`, and `PX to SP` conversions. – Suragch Feb 08 '17 at 08:37

3 Answers3

145

Use this

public static float pixelsToSp(Context context, float px) {
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

If you wanna test if this method works right use this snippet

XML

<TextView
        android:id="@+id/txtHelloWorld"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

<TextView
        android:id="@+id/txtHelloWorld2"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Java

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView helloWorldTextView = (TextView)    rootView.findViewById(R.id.txtHelloWorld);
TextView helloWorldTextView2 = (TextView) rootView.findViewById(R.id.txtHelloWorld2);
helloWorldTextView2.setTextSize(pixelsToSp(getActivity(), helloWorldTextView.getTextSize()));

Both TextView's font size should be same.

sealskej
  • 7,281
  • 12
  • 53
  • 64
48

See the DisplayMetrics class, it has fields for densityDpi and scaledDensity.

Example usage:

float sp = px / getResources().getDisplayMetrics().scaledDensity;
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • 2
    Just to clarify: the `DisplayMetrics` class has _fields_ `densityDpi` and `scaledDensity`, not methods. And for scaling, one would want to use the `density` field rather than `densityDpi`. – Ted Hopp Apr 12 '16 at 16:58
  • Please answer the question asked. Saying the name of a class that can be used for an answer is not itself an answer. – Megakoresh Dec 16 '16 at 12:50
5

weird to see public field that is adjusted at run time but it works. Standard Dpi is 160 so whatever your device Dpi is, say 240, both density and scaledDensity will show 240/160=1.5 This is how you convert between pixels and sp: px=1.5*sp

Vlad
  • 4,425
  • 1
  • 30
  • 39