Reputation: 12566
I have a simple class, BoundedView
that extends View
. I'm doing this primarily to mess with the onTouchEvent
callback function.
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?
Implementation:
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;
}
}
Using:
<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"/>
EDIT: This gets me close:
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 );
}
However, it is drawing a fully filled in black box, not a transparent one with a black border.
EDIT 2: Got it:
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 );
EDIT 3: Andreas and Warren's solution was much nicer:
@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 );
}
Upvotes: 2
Views: 5612
Reputation: 57702
Yes inside your onDraw()
is the right place.
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
That should work. If you set the paint
variable correctly (stroke width, color) you should see your border.
Upvotes: 5