Android利用shape画虚线,这个虚线还行

先上效果图:

Android利用shape画虚线,这个虚线还行


我们知道,想在Android XML中画出一条直线,很简单:

[html] view plain copy
  1. <View  
  2.      android:layout_width="match_parent"  
  3.      android:layout_height="1px"  
  4.      android:background="#FFFFFF"/>  


如果想要画出一条虚线呢?

在drawable目录下新建bg_dash_line.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="line">  
  4.     <stroke  
  5.         android:width="3px"  
  6.         android:color="#FFFFFF"  
  7.         android:dashWidth="10px"  
  8.         android:dashGap="10px" />  
  9. </shape>  

说明:

显示一条虚线,width为线条的高度,dashWidth为破折线的宽度,dashGap为破折线之间的空隙的宽度,当dashGap=0时,就是实线

注意:

1. 如果在<stroke>标签中设置了android:width,则在<View>标签中android:layout_height的值必须大于android:width的值,否则虚线不会显示。如果不设置,默认android:width为0。

2. 关于4.0以上设备虚线会变实线的问题:

代码中可以添加:

[java] view plaincopyAndroid利用shape画虚线,这个虚线还行Android利用shape画虚线,这个虚线还行
  1. line.setLayerType(View.LAYER_TYPE_SOFTWARE, null);  
XML中可以添加:

[html] view plaincopyAndroid利用shape画虚线,这个虚线还行Android利用shape画虚线,这个虚线还行
  1. android:layerType="software"  

如上例所示,如果想正常的显示虚线:

[html] view plain copy
  1. <View  
  2.      android:layout_width="match_parent"  
  3.      android:layout_height="4px"  
  4.      android:layerType="software"  
  5.      android:background="@drawable/bg_dash_line"/>