我有时要向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方法永远不会调用?
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
我遇到了同样的问题,我终于找到了问题所在......它与Android操作系统有关,我使用的是2.2,当我切换到2.3.X时,它有效...