android自定义能画出虚线效果的控件

虚线可以用背景图片来实现,但是我喜欢用代码实现,通过自定义view可以实现在界面上添加虚线功能,自定义view代码为:

public class DashedLineView extends View {  
    public DashedLineView(Context context, AttributeSet attrs) {  
        super(context, attrs);            
    }  
    @Override  
    protected void onDraw(Canvas canvas) {  
        // TODO Auto-generated method stub  
        super.onDraw(canvas);          
        Paint paint = new Paint();  
        paint.setStyle(Paint.Style.STROKE);  
        paint.setColor(Color.DKGRAY);  
        Path path = new Path();       
        path.moveTo(0, 10);  
        path.lineTo(480,10);        
        PathEffect effects = new DashPathEffect(new float\[\]{5,5,5,5},1);  
        paint.setPathEffect(effects);  
        canvas.drawPath(path, paint);  
    }
}

之后只要在布局文件中声明view就可以使用了,例如:

<com.android.pennote.DashedLineView
android:layout_height="20px"
android:id="@+id/dashed"         
android:layout_width="wrap_content"/>

下面是我将该自定义控件运用在app中的例子,效果如下: