onCreateDrawableState never call

混江龙づ霸主 提交于 2019-12-08 22:10:04

问题


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?


回答1:


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);
    }

}



回答2:


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...



来源:https://stackoverflow.com/questions/10223871/oncreatedrawablestate-never-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!