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.