我认为我已经找到了一个更加简洁的解决方案——创建一个自定义视图,其中包含特定代码来绘制虚线(在垂直和水平方向上),以及一堆属性,使得从XML布局中使用它非常容易。这种方法相对于“旋转线”的方法的主要优点是,您可以像通常那样设置虚线视图的大小,而不必担心旋转后视图的行为方式(因为旋转应用于整个虚线视图,而不仅仅是正在绘制的线)。
所以,这是逐步解决方案:
1. 创建文件“/res/values/attrs.xml”,并将以下内容复制到该文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DividerView">
<attr name="color" format="color" />
<attr name="dashLength" format="dimension" />
<attr name="dashGap" format="dimension" />
<attr name="dashThickness" format="dimension" />
<attr name="orientation" format="enum">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
</resources>
这将创建控制自定义视图的属性。
注意:如果上述文件已经存在于您的项目中,请将“declare-stylable”块复制/粘贴到现有的“resources”块内。
创建一个名为DividerView的类并粘贴下面的内容:
public class DividerView extends View {
static public int ORIENTATION_HORIZONTAL = 0;
static public int ORIENTATION_VERTICAL = 1;
private Paint mPaint;
private int orientation;
public DividerView(Context context, AttributeSet attrs) {
super(context, attrs);
int dashGap, dashLength, dashThickness;
int color;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DividerView, 0, 0);
try {
dashGap = a.getDimensionPixelSize(R.styleable.DividerView_dashGap, 5);
dashLength = a.getDimensionPixelSize(R.styleable.DividerView_dashLength, 5);
dashThickness = a.getDimensionPixelSize(R.styleable.DividerView_dashThickness, 3);
color = a.getColor(R.styleable.DividerView_color, 0xff000000);
orientation = a.getInt(R.styleable.DividerView_orientation, ORIENTATION_HORIZONTAL);
} finally {
a.recycle();
}
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(dashThickness);
mPaint.setPathEffect(new DashPathEffect(new float[] { dashLength, dashGap, }, 0));
}
public DividerView(Context context) {
this(context, null);
}
@Override
protected void onDraw(Canvas canvas) {
if (orientation == ORIENTATION_HORIZONTAL) {
float center = getHeight() * .5f;
canvas.drawLine(0, center, getWidth(), center, mPaint);
} else {
float center = getWidth() * .5f;
canvas.drawLine(center, 0, center, getHeight(), mPaint);
}
}
}
为了在布局文件中使用属性自动完成功能,请在顶层容器中添加以下名称空间定义:
xmlns:custom="http://schemas.android.com/apk/res/com.example"
将com.example
替换为您的包名。您还可以更改custom
为任何前缀,以更好地满足您的需求。
注意:在attrs.xml文件更改后,您可能需要重新启动Eclipse才能使自动完成功能正常工作。
最后,通过在布局中插入以下元素来创建虚线,就像其他视图一样:
<com.example.DividerView
android:layout_width="1dp"
android:layout_height="fill_parent"
android:layerType="software"
custom:color="@color/grey"
custom:orientation="vertical"
custom:dashLength="1dp"
custom:dashGap="1dp"
custom:dashThickness="1dp" />
希望这能有所帮助!