背景としてドローアブルを持つ TextView があります。StateListDrawable オブジェクトを使用して、プログラムで背景色を設定しようとしていますが、予期しない動作に遭遇しています。あるオブジェクトで色を設定すると、別のオブジェクトで色が変わります。これは不可能なはずです。
関連するコード:
GradientDrawable notPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
GradientDrawable isPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
isPressed.setColor(util.getColour(api, this));
StateListDrawable bg = new StateListDrawable();
// bg.addState(new int[] { android.R.attr.state_pressed }, isPressed);
bg.addState(StateSet.WILD_CARD, notPressed);
textView.setBackgroundDrawable(bg);
ドローアブル:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1dp" android:color="@color/divider" />
<solid android:color="@color/background_button" />
</shape>
util.getColour
api の値に基づいてカラー リソースを返します。
奇妙なことに、上記のコードではisPressed
ドローアブルの色が設定されていますが、その後、このドローアブルは使用されません。代わりに、notPressed
ドローアブルのみが textView の背景に追加されます。
ただし、textView の背景色は、isPressed
代わりにドローアブルの色になります! 同じドローアブル リソースから作成されたとしても、これらは 2 つの異なるオブジェクトである必要があるため、これは不可能です。