ボタンの背景をダイナミックに変える
|Androidではボタンを押した場合や離した場合と、ボタンの状態によって背景をダイナミックに変えることができます。
これは「State List」というリソースを使うことで簡単に実現できます。
あらかじめボタンに使う画像ファイルを/res/drawableに追加しておきます。
次に/res/drawableにbutton.xmlというxmlファイルを作ります。
1 2 3 4 5 6 7 8 9 10 11 | <?xml version= "1.0" encoding= "utf-8" ?> <!-- pressed --> <item android:state_pressed= "true" android:drawable= "@drawable/lilastoy" /> <!-- released --> <item android:state_pressed= "false" android:drawable= "@drawable/toothtoy" /> </selector> |
state_pressedがtrueもしくはfalse、つまりボタンが押されている、押されていないという状態ごとに
drawableで指定する画像ファイルを変えています。
あとは、ボタンビューの背景にbutton.xmlを指定すればOKです。
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version= "1.0" encoding= "utf-8" ?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:gravity= "center" > <Button android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:background= "@drawable/button" /> /> </LinearLayout> |
これを動作させると以下の画像のようになります。
7 Comments