230

Java コードを使用して特定のテキスト サイズを変更するために整数値を割り当てるとTextView、値はピクセル ( ) として解釈されpxます。

で割り当てる方法を知っている人はいspますか?

4

11 に答える 11

579

http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29

例:

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
于 2011-08-19T07:37:45.120 に答える
41

よりクリーンで再利用可能なアプローチは

ディレクトリ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));
于 2016-09-15T09:56:30.547 に答える
37

属性を使用して、DisplayMetricsオブジェクトを使用して、ピクセルとスケーリングされたピクセルの間の変換を支援できます。scaledDensity

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
于 2010-01-15T06:42:32.097 に答える
20

のソースコードに基づく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です。

于 2013-02-26T06:50:19.057 に答える
15

受け入れられた回答が機能しない場合 (たとえば、ペイントを扱う場合)、次を使用できます。

float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);
于 2015-02-14T16:23:37.453 に答える
13

デフォルトでは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.
于 2013-02-11T23:20:49.623 に答える
12

@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 に定義した場合です。

  1. 非 HD デバイス: desiredSp は 25 のまま、密度 = 1
  2. HD デバイス (Nexus 7 第 2 世代など): desiredSp が 50 っぽい、密度 = 2
于 2015-03-30T15:01:54.713 に答える