title: Android - Custom View Border
body: <p>I have a simple class, <code>BoundedView</code> that extends <code>View</code>. I'm doing this primarily to mess with the <code>onTouchEvent</code> callback function.</p>
  
  <p>Is there a way to draw a border around each instance of this view, from the class itself? If not, what is the easiest way to implement this?</p>
  
  <p>Implementation:</p>
  
  <pre><code>public class BoundedView extends View
  {
    public String cellName = "no name";
  
    // constructors are here.
  
    @Override
    public void onDraw( Canvas canvas )
    {
      // maybe here? Right now it's invisible, used only for touch detection
    }
  
    @Override
    public boolean onTouchEvent( MotionEvent event )
    {
      Intent i = new Intent( getContext(), TabCellDetails.class );
      i.putExtra( "cellName", this.cellName );
      getContext().startActivity( i );
  
      return false;
    }
  }
  </code></pre>
  
  <p>Using:</p>
  
  <pre><code>&lt;com.lifecoderdev.android.drawing1.BoundedView
          android:id="@+id/boundedView1"
          android:layout_width="70dp"
          android:layout_height="70dp"
          android:layout_alignParentBottom="true"
          android:layout_alignParentRight="true"
          android:layout_marginBottom="78dp"
          android:layout_marginRight="96dp" 
          android:tag="Smooth Endoplasmic Reticulum"/&gt;
  </code></pre>
  
  <p><strong>EDIT:</strong> <a href="http://upshots.org/android/android-easy-backgrounds-and-borders-for-views" rel="nofollow">This</a> gets me close:</p>
  
  <pre><code>public void onDraw( Canvas canvas )
  {
    int[] colors = { 0xFF000000, 0xCC000000 };
    float[] radii = { 5, 5, 5, 5, 5, 5, 5, 5 };
    GradientDrawable drawable = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, colors );
    drawable.setCornerRadii( radii );
    drawable.setStroke( 1, 0xFF000000 );
    this.setBackgroundDrawable( drawable );
  }
  </code></pre>
  
  <p>However, it is drawing a fully filled in black box, not a transparent one with a black border.</p>
  
  <p><strong>EDIT 2:</strong> Got it:</p>
  
  <pre><code>Paint paint = new Paint();
  
  paint.setColor( Color.RED );
  paint.setStrokeWidth( 1.0f );
  
  canvas.drawRect( 0, 0, getWidth(), 1.0f, paint );
  canvas.drawRect( 0, 0, 1.0f, getHeight(), paint );
  canvas.drawRect( 0, getHeight()-1.0f, getWidth(), getHeight(), paint );
  canvas.drawRect( getWidth()-1.0f, 0, getHeight(), getWidth(), paint );
  </code></pre>
  
  <p><strong>EDIT 3:</strong> Andreas and Warren's solution was much nicer:</p>
  
  <pre><code>@Override
  public void onDraw( Canvas canvas )
  {
    Paint paint = new Paint();
    paint.setColor( Color.RED );
    paint.setStrokeWidth( 1.5f );
    paint.setStyle( Style.STROKE );
  
    canvas.drawRect( 0, 0, getWidth(), getHeight(), paint );
  }
  </code></pre>