
以下のように dimens.xml に 定義したテキストサイズを指定する際に
レイアウトで指定する方法はわかると思います。
コードから指定する方法も
TextView#setTextSize(float)は数値を渡すだけなのでわかると思います。
しかし、 getResources().getDimension(R.dimen.textSize) の値を渡すと
意図しないサイズになります。
これは Resources#getDimension()で解像度別のサイズに変換されるためです。
そのため TextView#setTextSize(int, float)でピクセル単位としてサイズを指定する必要があります。
まとめ
<resources> <dimen name="textSize">18sp</dimen> </resources>
レイアウトで指定
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="@dimen/textSize" />
コードで指定(1)
textView.setTextSize(18);
コードで指定(2)
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.textSize));
参考: dimens.xmlを使ってテキストサイズ指定 – Android – ごろつきめも
おまけ: ユーザー設定の文字サイズに影響されない文字サイズ指定方法
float density = getResources().getDisplayMetrics().density; float scaledDensity = getResources().getDisplayMetrics().scaledDensity; float scale = scaledDensity / density; textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.textSize) / scale);




左から、[設定 > 画面設定 > フォントサイズ] を小・中・大・特大にした結果です。
demo の上2行はユーザー設定によって文字サイズが変わっていますが、
一番下の行はユーザー設定の文字サイズに影響されず固定サイズになっています。
文字サイズが変更できないのはユーザーの意思を無視することになるので微妙かもしれませんが、
タイトルやタブのテキストなど表示領域に制限があり、
文字サイズが大きくなるとレイアウトが崩れる場合はこのように指定するのもアリかもしれません。
参考: Y.A.M の 雑記帳: Android TextView の setTextSize() は sp 単位だよ!
ユーザー設定の文字サイズ変更でレイアウトが崩れないかがテスト項目に追加されました。← New!
こういった View がちゃんと表示されているかのテストってやっぱり人が確認するしかないんですかね…
OpenCV とかで画像処理で正常な画面と比較して〜みたいなのを見た覚えがあるけどそこまでしなくてはダメなのかなぁ。
追記: 2014/05/08
ユーザー設定の文字サイズの倍率を頑張って計算していましたが以下のコードで取得できることがわかりました。float scale = getResources().getConfiguration().fontScale;