onCreateDrawableState never call

2019-06-20 04:54发布

I have tye to add new state to RelativeLayout but onCreateDrawableState method is never call.

My class is:

public class UnreadableRelativeLayout extends RelativeLayout 
{
private static final int[] STATE_UNREADED = {R.attr.state_unreaded};
private boolean isUnreaded = false;

public UnreadableRelativeLayout(Context context) 
{
    super(context);
}

public UnreadableRelativeLayout(Context context, AttributeSet attrs) 
{
    super(context, attrs);
}

public UnreadableRelativeLayout(Context context, AttributeSet attrs, int defStyle) 
{
    super(context, attrs, defStyle);
}

public void setUnreaded(boolean isUnreaded) 
{
    if (this.isUnreaded != isUnreaded)
    {
        this.isUnreaded = isUnreaded;
        refreshDrawableState();
    }
}

@Override
protected int[] onCreateDrawableState(int extraSpace) 
{
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
    if (isUnreaded) mergeDrawableStates(drawableState, STATE_UNREADED);
    return drawableState;
}

}

Why onCreateDrawableState method never call?

2条回答
三岁会撩人
2楼-- · 2019-06-20 05:38

I had the same problem and I finally found what the problem was...It's related with the Android OS, I was using 2.2 and when I switched to 2.3.X it worked...

查看更多
Summer. ? 凉城
3楼-- · 2019-06-20 05:55

Try to create separate layout with android:duplicateParentState="true" and inflate it in your class. It works for me on Android 4.0.4:

unreadable_relative_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:duplicateParentState="true" >
    ...
</RelativeLayout>

UnreadableRelativeLayout.java:

public class UnreadableRelativeLayout extends RelativeLayout {

    public UnreadableRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater factory = LayoutInflater.from(context);
        factory.inflate(R.layout.unreadable_relative_layout, this);
    }

}
查看更多
登录 后发表回答