我有一个带有自定义状态的ImageView子类。实例化窗口小部件时,不会调用onCreateDrawableState,并且图像图形不会出现在我的布局中。即使我调用了refreshDrawableState(),它也不起作用。我单步执行后者并且View代码期望m_background已经设置(在我的情况下它仍然是null)。
我错过了什么会导致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>
可绘/ 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>
答案 0 :(得分:0)
你在com.example.test.Toggle
中错过了android:background="@drawable/selector_toggle.xml"
<com.example.test.Toggle
android:id="@+id/toggle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/selector_toggle.xml"
myapp:state_left="true"
/>