在android中,畫實線可以利用view+底色+1px長或寬,來進行布局配置;但對於虛線,沒有可以直接利用的虛線控制項,也沒有利用現有控制項的比較好的實現方式。要想實現虛線,不外乎兩種方式,一種是利用圖片來實現,另一種就是利用畫布畫虛線來實現。利用圖片的方式我就不介紹了,在這裡介紹第二種方式,也就是利用畫布來做。
首先我們定義一個類繼承自View,在onDraw方法裡面利用畫布畫出虛線,代碼如下所示:
[java]
package cn.emag.utils.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.util.AttributeSet;
import android.view.View;
public class CustomDashedLineView extends View {
public CustomDashedLineView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(getResources().getColor(Color.BLACK));
Path path = new Path();
path.moveTo(0, 5);
path.lineTo(this.getWidth(), 5);
PathEffect effects = new DashPathEffect(new float[] { 5, 5, 5, 5 }, 1);
paint.setPathEffect(effects);
canvas.drawPath(path, paint);
}
}
package cn.emag.utils.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.util.AttributeSet;
import android.view.View;
public class CustomDashedLineView extends View {
public CustomDashedLineView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(getResources().getColor(Color.BLACK));
Path path = new Path();
path.moveTo(0, 5);
path.lineTo(this.getWidth(), 5);
PathEffect effects = new DashPathEffect(new float[] { 5, 5, 5, 5 }, 1);
paint.setPathEffect(effects);
canvas.drawPath(path, paint);
}
}
在layout中使用:
[html]
<cn.emag.gaoju.view.DashedLineView
android:layout_width="match_parent"
android:layout_height="10dp" >
</cn.emag.gaoju.view.DashedLineView>
<cn.emag.gaoju.view.DashedLineView
android:layout_width="match_parent"
android:layout_height="10dp" >
</cn.emag.gaoju.view.DashedLineView>
當然,對於虛線的樣式,可以通過樣式來傳參數進去,進行控制,由於各個應用的需求都不一樣,這裡就不展開了。