6

我必须向 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 方法从不调用?

4

2 回答 2

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>

不可读的RelativeLayout.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);
    }

}
于 2013-06-20T23:00:28.983 回答
0

我遇到了同样的问题,我终于找到了问题所在......它与Android OS有关,我使用的是2.2,当我切换到2.3.X时它工作......

于 2012-06-11T13:34:56.723 回答