GettingSignals

[Android]selectorをJavaで書く

2012年11月16日
Posted by hina

selector使うと、
ボタン押したときの画像を変更できたりします。
とても、便利。

今回は、
XMLで定義しないで、プログラム上でselectorを行う方法です。

使うのは、StateListDrawableクラス。

http://developer.android.com/intl/ja/reference/android/graphics/drawable/StateListDrawable.html

使い方
        Drawable iconOn = /* Drawble 作成する */;
        Drawable iconOff = /* Drawble 作成する */;
        
        // StateListDrawable に状態と表示するDrawable をセット
        StateListDrawable d = new StateListDrawable();
        d.addState( new int[]{ android.R.attr.state_selected }, iconOn );
        d.addState( new int[]{ -android.R.attr.state_selected }, iconOff );
状態は、
new int[] { android.R.attr_state_xxxxx}
という形で指定します。
状態が無効のときは、マイナスを付ける
new int[] { android.R.attr_state_xxxxx}
あとは、Viewにセットするだけです。
Share

Comments are currently closed.

Follow

カレンダー

2024年4月
1234567
891011121314
15161718192021
22232425262728
2930