How rotate line in Android XML?

Don Rhummy picture Don Rhummy · Mar 6, 2013 · Viewed 32.4k times · Source

I'm trying to draw a diagonal line in an Android app with the XML, but it is not working. It simply draws a horizontal line.

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".TestActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" 
        style="@style/diagonalStyle">
    </RelativeLayout>

</RelativeLayout>

styles.xml:

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

    <style name="diagonalStyle">
        <item name="android:background">@drawable/background</item>
    </style>

</resources>

background.xml:

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

    <item>
        <rotate
            android:fromDegrees="0"
            android:toDegrees="45"
            android:pivotX="50%"
            android:pivotY="50%" >
            <shape
                android:shape="line"
                android:top="1dip" >
                <stroke
                    android:width="1dip"
                    android:color="#FF0000" />
            </shape>
        </rotate>
    </item>

</layer-list>

Answer

HalR picture HalR · Mar 6, 2013

You really only needed one number change to get it to work. Just Change the fromDegrees to 45:

<item>
    <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="50%"
            android:pivotY="50%" >
        <shape
                android:shape="line"
                android:top="1dip" >
            <stroke
                    android:width="1dip"
                    android:color="#FF0000" />
        </shape>
    </rotate>
</item>

The rotate drawable http://developer.android.com/reference/android/graphics/drawable/RotateDrawable.html

actually uses the Property Animation format http://developer.android.com/guide/topics/resources/animation-resource.html

Whereas you are making a non-animating diagonal line, you want it to start out at 45 degrees, and end up at 45 degrees also. So setting them both to 45 is the norm.