title: How to manage lifecycle in a ViewGroup-derived class?
body: <p>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 <code>GraphView</code> class:</p>
  
  <pre><code>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
      }
          .
          .
          .
  }
  </code></pre>
  
  <p>Moving stuff into this new <code>LinearLayout</code>-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).</p>
  
  <p>Coming from a MS Windows background, I kind of expected to find overridable <code>onCreate()</code> and <code>onDestroy()</code> 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.</p>
  
  <p>I ended up adding two additional public methods to my view: <code>start()</code> and <code>stop()</code>. I make these calls from the activity's <code>onResume()</code> and <code>onPause()</code> methods respectively.</p>
  
  <p>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...</p>