2010-09-26 111 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