I have a layout that has some special states (like being checked/pressed), and I wish to set its children to apply their own drawables based on this layout.
i'm searching for an alternative of setting duplicateParentState to true for each of its children (and maybe even all of its descendants).
I've tried to make the custom view have an attribute of setting it to each of its children, but i couldn't find in which method call to apply this attribute to all of its children. in each method i've tried, it either returns 0 for getChildCount() or it just doesn't do anything to the child itself ( using setDuplicateParentStateEnabled() ) .
as the documentation says , using setDuplicateParentStateEnabled won't do anything on the cases i need it from :
Note: in the current implementation, setting this property to true after the view was added to a ViewGroup might have no effect at all. This property should always be used from XML or set to true before adding this view to a ViewGroup.
so it seems i use it too late, but i need to call it late since the children don't exist yet in the parent...
How can I achieve this functionality of avoiding setting duplicateParentState for each child, and just set it to the parent view?
How about extending the widget -like you said- and overriding onLayout()? This way you ensure to modify the children state also the first time the widget is drawn. When onLayout() is called, getChildCount() will always return the actual number of children. For example:
public class LinearLayout extends android.widget.LinearLayout {
private static final int[] VIEW_GROUP_ATTRS = new int[]{ android.R.attr.enabled };
private static final boolean DEFAULT_IS_ENABLED = true;
private boolean isEnabled = DEFAULT_IS_ENABLED;
public LinearLayout(Context context) {
super(context);
}
public LinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
isEnabled = context.obtainStyledAttributes(attrs, VIEW_GROUP_ATTRS).getBoolean(0, DEFAULT_IS_ENABLED);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
this.isEnabled = enabled;
for (int i = 0; i < getChildCount(); ++i) {
getChildAt(i).setEnabled(enabled);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
setEnabled(isEnabled);
}
}
Note that you are actually extending the widget (calling super on any method being overridden).