Androidアプリ開発でXMLを編集している時、@color/blackのような@を使う形式以外に?attrという?を使う形式があります。
今回はこの?について調べてみました。
?attrですが、こちらはThemeの属性になります。
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?android:attr/statusBarColor" app:popupTheme="@style/Theme.MyApplication.PopupOverlay" />
属性はThemeで下のように定義します。
Theme毎に違う値をセットできるので、動的にThemeを変更する時などに使うと便利そうです。
<resources xmlns:tools="http://schemas.android.com/tools"> <style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <item name="android:statusBarColor">#888</item> </style> </resources
もしthemeの属性を増やしたい場合res/values/attrs.xmlで下のように定義します。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyAttrs"> <attr name="customColor" format="color" /> <attr name="customValue" format="integer" /> </declare-styleable> </resources>
定義する事で下のように利用できるようになります。
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <item name="customColor">#fff</item> </style>