4

コードで作成した ColorStateList を TextView の TextColor として適用しようとしています。問題は、xml で定義された ColorStateList を使用すると機能するが、コードで ColorStateList を作成すると機能しないことです。

ColorStateList を作成する方法は次のとおりです。

int[][] states = new int[][] { new int[] { android.R.attr.state_activated } };

int[] colors = new int[] { Color.parseColor("#FFFF00") };

myList = new ColorStateList(states, colors);

この方法でこれを TextView に簡単に適用します

myTextView.setTextColor(myList);

動作しません。このxmlの使用

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_activated="true"  android:color="@color/yellow" />
   <item android:color="@color/black" />
</selector>

xmlでテキストの色を設定するか、このようにコードで動作します

myTextView.setTextColor(myTextView.getContext().getResources().getColorStateList(R.drawable.textcolor_selector));

Web で解決策を検索しましたが、この問題の原因が本当にわかりません。誰か助けてもらえますか?

ありがとうございました

4

1 に答える 1

2

状態リストにデフォルト値を追加する必要があるかもしれません。あなたの場合、state_activated の反対の状態:

int[][] states = new int[][] { new int[] { android.R.attr.state_activated }, new int[] { -android.R.attr.state_activated } };
int[] colors = new int[] { Color.parseColor("#FFFF00"), Color.BLACK };
myList = new ColorStateList(states, colors);
于 2014-11-22T18:54:55.737 に答える