1. 程式人生 > >Android 關於shape畫虛線

Android 關於shape畫虛線

前言:平時我們經常使用shape用來繪製背景圖,通常的用法確實沒有什麼問題,但是你遇到過畫虛線嘛?

實現虛線的shape畫法:
shape_dash_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <size android:height="1dp" />
    <stroke
        android:dashGap="3dp"
android:dashWidth="8dp" android:width="1dp" android:color="#848C99" /> </shape>

這是很普遍的寫法,相信大家都會寫。

然後寫個 view ,設定它的 background 為 @draw/shape_dash_line ,然而卻發現在 Android Studio 預覽面板上並沒有顯示這條虛線。

<View
    android:id="@+id/line"
    android:layout_width="match_parent"
    android:layout_height="1dp"
android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@drawable/shape_dash_line"/>
image.png

問題1:畫的虛線為什麼沒有顯示出來?

解答:原因在於設定的 view 的高度與 shape 虛線的高度相同。因此不會顯示,只需要將 view 中的 layout_height 設定的比 shape 虛線的高度大就可以。例如:將 layout_height=“1dp” 改為 layout_height=“1.5dp” 。

這時,Android Studio 的預覽面板就出現了這條虛線。

image.png

好,此時執行到真機當中,卻發現在真機上顯示的卻是一條實線。

問題2:本該顯示的虛線,為什麼顯示為實線?

解答:原因在於 Android 3.0 之後,系統預設關閉了硬體加速功能。所以你可以使用以下方法。

  1. view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

  2. 在AndroidManifest檔案中,在需要用到虛線的activity的新增屬性

    <activity android:hardwareAccelerated="false" />