Java コードを使用して特定のテキスト サイズを変更するために整数値を割り当てるとTextView
、値はピクセル ( ) として解釈されpx
ます。
で割り当てる方法を知っている人はいsp
ますか?
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
例:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
よりクリーンで再利用可能なアプローチは
ディレクトリdimens.xml
内のファイルのテキスト サイズを定義します。res/values/
</resources>
<dimen name="text_medium">14sp</dimen>
</resources>
そしてそれをに適用しますTextView
:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));
属性を使用して、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()));
}
ピクセルに対する任意の寸法を計算するために、この関数を作成します。
int getPixels(int unit, float size) {
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
return (int)TypedValue.applyDimension(unit, size, metrics);
}
unit は のようなものTypedValue.COMPLEX_UNIT_SP
です。
受け入れられた回答が機能しない場合 (たとえば、ペイントを扱う場合)、次を使用できます。
float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);
デフォルトでは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 に定義した場合です。