Button や ImageButton をフォーカスがあるときやボタンを押された時に表示を変更について説明します。
ここでは、ImageButton について説明します。まず、通常状態のボタン画像(ファイル名:btn_mouseout.png、リソースID:btn_mouseout)とボタンを押された時の画像(ファイル名:btn_mouseover.png、リソースID:btn_mouseover)を用意します。
最初に xml 定義で selector 要素で、ボタンの状態による表示の振舞いを記述(ファイル名:btn_state.xml、リソースID:btn_state)します。
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <!-- ボタンを押された時 --> <item android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/btn_mouseover"/> <!-- ボタンにフォーカスがあたった時 --> <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_mouseout"> <!-- 上記以外の条件の時 --> <item android:state_enabled="true" android:drawable="@drawable/btn_mouseout"> </selector> |
つぎにスタイル定義している xml に記述(ファイル名:style.xml、リソースID:style)します。
<?xml version="1.0" encoding="utf-8"?> <resources> : <style name="style_btn"> <item name="android:background">@drawable/btn_state</item> </style> : </resources> |
最後に、このボタンを使っているレイアウト定義ファイルにスタイルを定義します。
: <ImageButton android:id="@+id/btn_action" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/style_btn" /> : |