4

Does anyone know what the appropriate mechanism is when creating a custom compound control to apply state changes from the container down to all the children? It would seem to me there should be a straightforward way to set up a ViewGroup to forward all state changes (pressed, enabled, etc.) to each child.

For example, if I create a custom widget along the lines of:

public class MyWidget extends RelativeLayout {

    private TextView mTitleView, mValueView;
    private ImageView mImageView;

    public ValueButton(Context context) {
        this(context, null);
    }

    public ValueButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        //View setup, etc.
    }
}

In many cases, there are drawable or color state lists attached to the children that I want to toggle when changes apply to the overall widget as a whole. What do I need to add to a widget such as this so that when, for example, I call MyWidget.setEnabled() or when MyWidget is pressed those state changes filter down the hierarchy?

Thanks!

devunwired
  • 62,780
  • 12
  • 127
  • 139

2 Answers2

3

Add android:duplicateParentState="true" to each child (perhaps iterating through the childs using getChildAt(int index))

http://developer.android.com/reference/android/view/View.html#attr_android:duplicateParentState

Edit: you will need to set it up in the xml

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.

Aleadam
  • 40,203
  • 9
  • 86
  • 108
0

Not sure if I'm going to be much help here, but it's an interesting problem for me to think about because I think I'm going to want to do something quite similar.

In terms of cascading state information down to child Views, could one possible approach be to only contain that state information in the parent ViewGroup, and in the child Views make use of getParent() to access that information?

Trevor
  • 10,903
  • 5
  • 61
  • 84