title: How to write set methods of custom Views
body: <p>I have written a subclass of <code>View</code> and I have included a method to set a field. The value of the field affects the the size of the <code>View</code> and the contents of the <code>View</code>.</p>
  
  <p>What do I have to write in the <code>set</code> method to ensure that the view will be properly updated with immediate effect? I am asking because when I use my own custom views as part of a layout of a <code>ListView</code> item, I find that when I try to recycle my own views by using the <code>convertView</code> argument of an <code>ArrayAdapter</code>'s <code>getView</code> method, sometimes the <code>set</code> method doesn't seem to work.</p>
  
  <p>Here is a contrived example of the kind of thing I am trying to do. I have only just started learning how to extend <code>View</code>, so there may be other problems with this code.</p>
  
  <pre><code>public final class SpotsView extends View {
  
      private final MyActivity activity;
      private int numberOfSpots;
  
      public SpotsView(MyActivity activity) {
          super(activity);
          this.activity = activity;
      }
  
      public void setNumberOfSpots(int numberOfSpots) {
          this.numberOfSpots = numberOfSpots;
          // What do I have to write here?? invalidate()? forceLayout()?
      }
  
      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
          Resources resources = activity.getResources();
          setMeasuredDimension(
              (int) (numberOfSpots * resources.getDimension(R.dimen.block_width)),
              (int) resources.getDimension(R.dimen.spots_view_height)
          );
      }
  
      @Override
      protected void onDraw(Canvas canvas) {
          int height = getHeight();
          int width = getWidth();
          float radius = activity.getResources().getDimension(R.dimen.network_outer_radius);
          for (int i = 0; i &lt; numberOfSpots; i++)
              canvas.drawCircle((i + 0.5F) * (width / numberOfSpots), height * 0.5F, radius, activity.spotPaint());
      }
  } 
  </code></pre>