onCreateDrawableState永远不会调用(onCreateDrawableState

2019-09-16 15:35发布

我有塔伊到新的状态添加到RelativeLayout的,但onCreateDrawableState方法不会被调用。

我的类是:

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

}

为什么onCreateDrawableState方法从来没有打电话?

Answer 1:

尝试使用创建单独的布局android:duplicateParentState="true" ,并在你的类充气。 它为我在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);
    }

}


Answer 2:

我有同样的问题,我终于发现了问题是什么?它与Android操作系统相关的,我用的是2.2,当我切换到2.3.x版本,它的工作...



文章来源: onCreateDrawableState never call