6

I want to draw a vertical dotted line in xml, using shape.

I used this example:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="line">

<size
android:height="400dp"
android:width="4dp"/>

<stroke
        android:color="#000000"
        android:dashWidth="100dp"
        android:dashGap="10dp" />
</shape>

Then:

<View android:id="@+id/vertical_line"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/dotted_line"
      android:layout_marginLeft="27dp"/>

But it doesn't work. How can I do it?

krsteeve
  • 1,794
  • 4
  • 19
  • 29
Ihor Bykov
  • 1,843
  • 3
  • 15
  • 22

3 Answers3

31

I tried a few things, I liked the drawable solutions and found that this worked.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="-8dp"
    android:bottom="-8dp"
    android:left="-8dp">
    <shape>
        <solid android:color="@android:color/transparent"/>
        <stroke
            android:width="4dp"
            android:color="#df0000"
            android:dashGap="4dp"
            android:dashWidth="4dp"/>
    </shape>
</item>
</layer-list>

The trick is the negative top bottom and left values as these are set outside of the object now, leaving a single dashed line.

Its used in the following view.

<View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
Duncan Hoggan
  • 5,082
  • 3
  • 23
  • 29
3

Try this

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line" >

    <size
        android:height="400dp"
        android:width="4dp" />

    <stroke
        android:dashGap="10dp"
        android:dashWidth="100dp"
        android:color="#000000" />

</shape>

Then use like this

<LinearLayout
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@drawable/dot_line"
    android:orientation="vertical" >
</LinearLayout>
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
-2
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90" >

    <shape android:shape="line" >

    <stroke
        android:color="#000000"
        android:dashWidth="100dp"
        android:dashGap="10dp"/>
    </shape>

</rotate>
AnupamChugh
  • 1,779
  • 1
  • 25
  • 36
  • Seems like there's a bug when using rotate drawable in Android M and above as per the thread here : https://stackoverflow.com/a/8716798/3849039 – AnupamChugh Aug 09 '17 at 17:33