3

I wrote a little custom View and I'm wondering if it would be a good idea to register a listener for the underlying data model object in onAttachedToWindow() and unregister in onDetachedFromWindow().

Example code:

 public class CustomView extends View implements OnChangedListener {

    private DataObject data;

    public CustomView(Context context) {
        super(context);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (data != null) {
            data.addOnChangedListener(this);
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (data != null) {
            data.removeOnChangedListener(this);
        }
    }

    public void setData(DataObject newData) {

        if (this.data != null) {
            // Remove the listener from the old data
            this.data.removeOnChangedListener(this);
        }

        // Register the listener to the new data
        newData.addOnChangedListener(this);

        this.data = newData;

    }

    public void onChanged(DataObject data){
             // Update this UI component.
             // assumption: This one will always be invoked from the UI Thread
    }

}

I think it will work, but I'm not sure if this would be a good idea in general. I would like to use the CustomView in a ListView, where setData() will be called from the adapter. I don't think that it will have impact on performance and I guess that it will also not end in memory leaks.

Does anybody has build something similar or can tell me disadvantages of this architecture?

You may ask yourself why I do not simply make the Activity a OnChangedListener and call Adapter.notifyDatasetChanged()?

Well me too :D

I find it not a bad idea if there are more CustomViews, displaying the same DataObject, if they could be updated all at once automatically

4

0 回答 0