Drawable.setState()如何控制drawable的特定状态?

时间:2012-08-13 23:44:12

标签: android android-widget

我有这样的抽象:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_pressed" />

<item android:state_focused="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_selected" />

<item android:state_selected="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_selected" />

<item android:drawable="@drawable/seek_thumb_normal" />

在代码中,如何设置Drawable的特定状态?我想将它设置为state_pressed = true状态。

2 个答案:

答案 0 :(得分:22)

知道了。来自此处的评论有助于:Android : How to update the selector(StateListDrawable) programmatically

所以Drawable.setState()采用整数数组。这些整数表示可绘制的状态。您可以传递任何您想要的整数。一旦ints传入匹配状态列表中的“item”drawables,drawable就会在该状态下绘制。

在代码中更有意义:

int[] state = new int[] {android.R.attr.state_window_focused, android.R.attr.state_focused};
minThumb.setState(state);

请注意,我的状态列表drawable同时包含state_pressed="true"android:state_window_focused="true"。所以我必须将这两个int值都传递给setState。当我想清除它时,我只是minThumb.setState(new int[]{});

答案 1 :(得分:4)

没有足够的评论点,所以这只是android-developer所说的一个补充。对于诸如state_enabled之类的某些状态,没有明显的方法来设置该状态的相反值(例如,没有state_disabled)。要指示消极或相反的状态,只需传递该状态的资源的负值。

int[] state = new int[] {-android.R.attr.state_enabled}; //Essentially state_disabled

然后像往常一样将整数数组传递给setState()方法。

minThumb.setState(state);