2010-09-26 56 views
4

我試圖通過繪製自定義視圖來繪製自定義邊框。以下是邊框一側的示例:使用自定義視圖繪製邊框Android

package com.sparkydev.guessaphrase; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.drawable.ShapeDrawable; 
import android.graphics.drawable.shapes.RectShape; 
import android.util.AttributeSet; 
import android.view.View; 

public class LeftBorder extends View { 
    private ShapeDrawable vertRect, horizRect; 

    public LeftBorder(Context context, AttributeSet attributeset) { 
     super(context, attributeset); 

     int width = this.getWidth(); 
     int height = this.getHeight(); 

     vertRect = new ShapeDrawable(new RectShape()); 
      vertRect.getPaint().setColor(Color.RED); 
      vertRect.setBounds(0, 0, width/10, height); 
     horizRect = new ShapeDrawable(new RectShape()); 
      horizRect.getPaint().setColor(Color.RED); 
      horizRect.setBounds(0, 0, width, height/9); 

    } 

    protected void onDraw(Canvas canvas){ 
     vertRect.draw(canvas); 
     horizRect.draw(canvas); 
    } 

} 

而另一側的定義方式幾乎相同。 XML定義如下:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/wallpaper"> 


    <!-- Declares left border's position, which is 
    drawn programmatically.--> 
    <com.sparkydev.guessaphrase.LeftBorder 
     android:id="@+id/leftborder" 
     android:layout_alignParentLeft="true" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     /> 



     <!-- Used a FrameLayout to contain 
     the menu buttons.--> 
     <FrameLayout 
     android:id="@+id/FrameLayout01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     > 

      <!-- Menu buttons --> 

     </FrameLayout> 


    <!-- Declares right border position (on right 
    of screen, below the left border) --> 
    <com.sparkydev.guessaphrase.RightBorder 
     android:layout_alignParentRight="true" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/leftborder" 
    /> 



</RelativeLayout> 

問題是,邊界根本沒有出現。背景顯示,但沒有別的。

回答

10

the "Building Custom Components" dev guide開始,在創建自定義視圖時,它將具有100x100的設置大小,直到您另外指定爲止。看看這是否與你所看到的問題有關。

「你幾乎肯定要重寫onMeasure()和也可能需要重寫onDraw()如果希望組件顯示的東西。雖然都有默認的行爲,默認onDraw()會做什麼,並且默認onMeasure()將始終設置爲100x100的大小 - 這可能不是您想要的。「

+1

Hooray!謝謝。我會投你的答案,但我沒有足夠的聲譽。 – ramblinjan 2010-09-26 22:11:16

+0

如果解決問題,則可以將答案標記爲接受的答案。 ;-) – Brian 2010-09-26 22:13:44