2012年3月30日金曜日

Android テーマでデフォルトの sp 単位を置き換える

“本当は、きちんと sp 単位に対応すべきです”

しかし、これまでデフォルトの文字サイズ(android:textSize や setTextSize() してない widget の文字サイズ)でアプリを作成していたが、 sp 単位のことを考慮していなかったためにレイアウトが崩れるなどの現象がおこり、どうしてもデフォルトの文字単位を一括で dp にしたいこともあるでしょう。

デフォルトの文字サイズについては Android UI Cookbook for 4. 0 の 1.2.2 タイポグラフィに書いたので、詳しくはそっちを参照してください。

例えば、TextView のテーマを見てみると、

  1.     437     <style name="Widget.TextView">  
  2.     438         <item name="android:textAppearance">?android:attr/textAppearanceSmall</item>  
  3. ...  
  4.     448     </style>  

http://tools.oesf.biz/android-4.0.1_r1.0/xref/frameworks/base/core/res/res/values/styles.xml#437

のように、textAppearanceSmall という attr を参照しています。

  1.  42     <style name="Theme">  
  2.   
  3.  85         <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>  
  4.   
  5. 371     </style>  

http://tools.oesf.biz/android-4.0.1_r1.0/xref/frameworks/base/core/res/res/values/themes.xml#83

デフォルトのテーマでは textAppearanceSmall には @android:style/TextAppearance.Small が指定されており、 これは次のように 14sp になっています。

  1. 792     <style name="TextAppearance.Small">  
  2. 793         <item name="android:textSize">14sp</item>  
  3. 794         <item name="android:textColor">?textColorSecondary</item>  
  4. 795     </style>  


よって、オリジナルテーマで textAppearanceSmall を書き換えれば TextView のデフォルトの文字サイズを sp でなくすことができます。もちろん、textAppearanceSmall を参照している他の widget も影響を受けます。

  1. <style name="MyTheme" parent="@android:style/Theme">  
  2.     <item name="textAppearanceSmall">@style/MyTextAppearanceSmall</item>  
  3. </style>  
  4.   
  5. <style name="MyTextAppearanceSmall" parent="@android:style/TextAppearance.Small">  
  6.      <item name="android:textSize">14dp</item>  
  7. </style>  


デフォルトテーマで TextAppearance として定義されているのは small だけではありません。かなりいろいろありますが、 http://tools.oesf.biz/android-4.0.1_r1.0/xref/frameworks/base/core/res/res/values/themes.xml#83

  • textAppearanceLarge
  • textAppearanceMedium
  • textAppearanceSmall
  • textAppearanceLargeInverse
  • textAppearanceMediumInverse
  • textAppearanceSmallInverse


あたりをカバーすればだいたいの widget は影響範囲に入ります。
もちろん ActionBar のタブの文字サイズなど、影響範囲に入らないものは個別にスタイルを指定することになります。


0 件のコメント:

コメントを投稿