如何使用Java代码分配sp值的文本大小
如果我使用java代码分配整数值来更改TextView的某个文本大小,则该值将被解释为像素(px)。 现在有谁知道如何分配在SP?
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
例:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);  您可以使用DisplayMetrics对象来帮助使用scaledDensity属性在像素和缩放的像素之间进行转换。 
 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
 基于setTextSize的源代码: 
 public void setTextSize(int unit, float size) { Context c = getContext(); Resources r; if (c == null) r = Resources.getSystem(); else r = c.getResources(); setRawTextSize(TypedValue.applyDimension( unit, size, r.getDisplayMetrics())); } 
我build立这个函数来调用像素的任何尺寸:
 int getPixels(int unit, float size) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); return (int)TypedValue.applyDimension(unit, size, metrics); } 
 单元类似于TypedValue.COMPLEX_UNIT_SP 。 
更清洁,更可重用的方法是
 在res/values/目录下的dimens.xml文件中定义文本大小: 
 </resources> <dimen name="text_medium">14sp</dimen> </resources> 
 然后将其应用于TextView : 
 textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium)); 
默认情况下setTextSize,没有单位工作在SP(比例像素)
 public void setTextSize (float size) Added in API level 1 Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference. 
谢谢@John Leehey和@PeterH:
 desiredSp = getResources().getDimension(R.dimen.desired_sp); density = getResources().getDisplayMetrics().density; textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, desiredSp / density); 
问题是如果你在你的dimen.xml中定义R.dimen.desired_sp为25
- 在非HD设备上:desiredSp仍然是25,密度= 1
- 在HD设备上(如Nexus 7第二代):desiredSp变为50 ish,密度= 2
如果接受的答案不起作用(例如,在处理“绘画”时),则可以使用:
 float spTextSize = 12; float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity; textPaint.setTextSize(textSize); 
 semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_size_in_dp)) 
这是将PX转换为SP格式的代码。 100%的作品
 view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);