我有一个带有自定义状态的ImageView子类。当小部件被实例化时,onCreateDrawableState不会被调用,并且图像图形不会出现在我的布局中。即使我调用refreshDrawableState(),它也不起作用。我单步执行了后者,View代码期望m_background已经设置(在我的情况下仍为空)。
我错过了什么,导致m_background没有初始值?
values/attrs.xml
<resources>
<declare-styleable
name="toggle_states">
<attr name="state_left" format="boolean"/>
<attr name="state_right" format="boolean"/>
</declare-styleable>
</resources>
drawables/selector_toggle.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.example.test" >
<item
myapp:state_left="true"
android:drawable="@drawable/toggle_left" />
<item
myapp:state_right="true"
android:drawable="@drawable/toggle_right" />
</selector>
Toggle.java
public class Toggle extends ImageView
{
private static final int[] STATE_LEFT = {R.attr.state_left};
private static final int[] STATE_RIGHT= {R.attr.state_right};
public enum State {LEFT, RIGHT};
private State state = State.LEFT;
public Toggle (Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
public int[] onCreateDrawableState (int extraSpace)
{
final int[] drawableState = super.onCreateDrawableState (extraSpace + 1);
if (state == State.LEFT)
mergeDrawableStates (drawableState, STATE_LEFT);
else
mergeDrawableStates (drawableState, STATE_RIGHT);
return drawableState;
}
}
some_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.example.test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
...
<com.example.test.Toggle
android:id="@+id/toggle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myapp:state_left="true"
/>
...
</LinearLayout>