R.style

これまで、ButtonやTextViewなどのViewにいろいろな属性を直接指定してきたが、styles.xmlにスタイルとしてまとめて設定しておけば、Viewのstyle属性にセットするだけで、そのスタイルのViewになる・・・。

スタイルとテーマ | Android Developers

Androidの既定のスタイルは、

R.style | Android Developers

にもあるが、まずは独自のスタイルを作ってまとめてみる・・・。

strings.xmlは、

文字列リソースだけでわかると思うが、Buttonを4つ用意する・・・。

f:id:BG1:20170104172055p:plain

drawableに矩形ボタンrectangle_button.xmlを追加・・・。

白地に赤枠の矩形ボタン・・・。

f:id:BG1:20170104172316p:plain

楕円ボタンoval_button.xmlも追加・・・。

黄色地に青枠の楕円ボタン・・・。

ここで、

f:id:BG1:20170104172549p:plain

既に用意してあるstyles.xmlを編集・・・。

AppBaseThemeとかAppThemeはもともと用意されているテーマ・・・。

CustomStyle_RectangleButtonは、赤い矩形ボタンのスタイル・・・。
styleタグのnameでスタイル名、itemタグのnameに変更したいView属性、値はitemタグの中に・・・。
このスタイルを指定すると、赤い矩形ボタンに・・・。

CustomStyle_OvalButtonは、青い楕円ボタンのスタイル・・・。
同様にView属性を変えてる・・・。

CustomStyle_RectangleButton2は、parentにCustomStyle_RectangleButtonを指定している・・・。
CustomStyle_RectangleButtonを親として、継承したスタイルであることを示している・・・。
android:backgroundは指定していないので、親を継承しているが、android:layout_widthとandroid:layout_heightは96dpと固定になっている・・・。
この部分だけ違うものになる・・・。

activity_main.xmlは、

Button1は、styleをセットしていない普通のButton・・・。
Button2は、styleにCustomStyle_RectangleButtonをセットし、layout_width, layout_height, backgroundなどは指定していない・・・。
Button3は、styleにCustomStyle_OvalButtonをセットし、他はButton2と同様に省略・・・。
Button4は、styleにCustomStyle_RectangleButton2をセットし、こちらも他は同様に省略・・・。

f:id:BG1:20170104173856p:plain

このように、指定したスタイル通りの形状になった・・・。

Sample/android/R.style/R.style/src/R.style at master · bg1bgst333/Sample · GitHub