How to set text size using dimension from xml at runtime programmatically?

Add dimension in dimens.xml:

   <dimen name="text_medium">18sp</dimen>

Set the size in code:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));

Both methods getDimensionPixelSize() and getDimension() use screen density to calculate pixels. Your phone screen density is obviously hdpi (240dpi) so it uses 1.5 scale to convert dp to sp. Simple math 18 * 1.5 = 27.

It seems that your tablet density is mdpi (160dpi) so scale is just 1:1.

But if you compare real size of both texts it should be the same.

The best way is just create two dimens.xml files one in values folder for phone, and another in values-sw600dp for tablets (you could use also values-sw720dp-land folder to store dimensions for 10 inch tablets in landscape orientation).

You could read more about dimensions in Android at: http://android4beginners.com/2013/07/appendix-c-everything-about-sizes-and-dimensions-in-android/