これが私のコードです:
public void setHoverEffect(final Button button,int normalImageId, int hoverImageId) {
if (button != null)
{
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{ }, getResources().getDrawable(normalImageId));
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(hoverImageId));
button.setBackgroundDrawable(stateListDrawable);
}
}
上記のコードを使用すると、通常の画像のみが背景として表示され、ボタンを押すとホバー画像が表示されません。
selector.xml
以下に示すようにファイルを使用して背景として設定すると、正常に動作します。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_ok_h"> </item>
<item android:drawable="@drawable/btn_ok"> </item>
</selector>
アプリケーションのすべてのボタンに対してセレクター xml ファイルを作成しないようにするために、これを動的に実行したいと考えています。コードのどこが間違っていたのか、どこに追加の属性を指定しなければならないのかわかりません... :(