How to manage lifecycle in a ViewGroup-derived class?

Posted by Scott Smith on Stack Overflow See other posts from Stack Overflow or by Scott Smith
Published on 2010-03-01T20:13:53Z Indexed on 2010/03/11 18:39 UTC
Read the original article Hit count: 206

Filed under:
|

I had a bunch of code in an activity that displays a running graph of some external data. As the activity code was getting kind of cluttered, I decided to extract this code and create a GraphView class:

public class GraphView extends LinearLayout {
    public GraphView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        inflater.inflate(R.layout.graph_view, this, true);
    }

    public void start() {
        // Perform initialization (bindings, timers, etc) here
    }

    public void stop() {
        // Unbind, destroy timers, yadda yadda
    }
        .
        .
        .
}

Moving stuff into this new LinearLayout-derived class was simple. But there was some lifecycle management code associated with creating and destroying timers and event listeners used by this graph (I didn't want this thing polling in the background if the activity was paused, for example).

Coming from a MS Windows background, I kind of expected to find overridable onCreate() and onDestroy() methods or something similar, but I haven't found anything of the sort in LinearLayout (or any of its inherited members). Having to leave all of this initialization code in the Activity, and then having to pass it into the view seemed like it defeated the original purpose of encapsulating all of this code into a reusable view.

I ended up adding two additional public methods to my view: start() and stop(). I make these calls from the activity's onResume() and onPause() methods respectively.

This seems to work, but it feels like I'm using duct tape here. Does anyone know how this is typically done? I feel like I'm missing something...

© Stack Overflow or respective owner

Related posts about android

Related posts about android-sdk