Android - 自定义视图边框

Jos*_*osh 2 java xml android border view

我有一个简单的类,BoundedView扩展View.我这样做主要是为了搞乱onTouchEvent回调函数.

有没有办法在类本身的每个实例周围绘制边框?如果没有,最简单的方法是什么?

执行:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

使用:

<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"/>
Run Code Online (Sandbox Code Playgroud)

编辑: 让我很接近:

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 );
}
Run Code Online (Sandbox Code Playgroud)

然而,它正在绘制一个完全填充的黑色框,而不是带有黑色边框的透明黑框.

编辑2:得到它:

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 );
Run Code Online (Sandbox Code Playgroud)

编辑3: Andreas和Warren的解决方案更好:

@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 );
}
Run Code Online (Sandbox Code Playgroud)

War*_*ith 5

是的,你onDraw()的内心是正确的地方.

canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
Run Code Online (Sandbox Code Playgroud)

这应该工作.如果paint正确设置变量(笔触宽度,颜色),您应该看到边框.

  • 试试"paint.setStyle(Style.STROKE)". (3认同)