2012-03-01 69 views
2

我有一個簡單的類,BoundedView,它擴展了View。我這樣做主要是爲了搞砸onTouchEvent回調函數。Android - 自定義視圖邊框

有沒有一種方法可以從類本身繪製該視圖的每個實例的邊框?如果不是,那麼實現這個最簡單的方法是什麼?

實現:

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; 
    } 
} 

使用:

<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"/> 

編輯:This讓我接近:

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); 
} 

但是,畫滿裝黑匣子,不是透明的,有黑色邊框。

編輯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); 

編輯3:安德烈亞斯和沃倫的解決方案是好得多:

@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); 
} 

回答

5

是裏面你onDraw()是正確的地方。

canvas.drawRect(0, 0, getWidth(), getHeight(), paint); 

這應該有效。如果您正確設置paint變量(筆劃寬度,顏色),您應該看到您的邊框。

+0

'Paint paint = new Paint(); paint.setColor(Color.BLACK); 012.Flash.setStrokeWidth(1.0f); canvas.drawRect(0,0,getWidth(),getHeight(),paint);' 只給了我一個黑色的方塊。我錯過了什麼嗎?我需要非邊界是透明的,因爲它背後有一個ImageView。 – Josh 2012-03-01 22:55:42

+3

嘗試「paint.setStyle(Style.STROKE)」。 – Andreas 2012-03-01 23:18:26

+0

@Andreas:謝謝,這完美的作品! – Josh 2012-03-01 23:40:09