Android利用shape畫虛線

我們知道,想在Android XML中畫出一條直線,很簡單:

<View
     android:layout_width="match_parent"
     android:layout_height="1px"
     android:background="#FFFFFF"/>


如果想要畫出一條虛線呢?

在drawable目錄下新建bg_dash_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="3px"
        android:color="#FFFFFF"
        android:dashWidth="10px"
        android:dashGap="10px" />
</shape>

說明:

顯示一條虛線,width爲線條的高度,dashWidth爲破折線的寬度,dashGap爲破折線之間的空隙的寬度,當dashGap=0時,就是實線

注意:

1. 如果在<stroke>標籤中設置了android:width,則在<View>標籤中android:layout_height的值必須大於android:width的值,否則虛線不會顯示。如果不設置,默認android:width爲0。

2. 關於4.0以上設備虛線會變實線的問題:

代碼中可以添加:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. line.setLayerType(View.LAYER_TYPE_SOFTWARE, null);  
XML中可以添加:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. android:layerType="software"  

如上例所示,如果想正常的顯示虛線:

<View
     android:layout_width="match_parent"
     android:layout_height="4px"
     android:layerType="software"
     android:background="@drawable/bg_dash_line"/>
發佈了65 篇原創文章 · 獲贊 26 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章