Android how to create triangle and rectangle shape programmatically?
Solution 1:
Here it is XML
for triangle
and rectangle
. save it inside drawable folder.
triangle.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item >
<rotate
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="-40%"
android:pivotY="87%" >
<shape
android:shape="rectangle" >
<stroke android:color="@android:color/transparent" android:width="10dp"/>
<solid
android:color="#000000" />
</shape>
</rotate>
</item>
</layer-list>
rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle">
<solid android:color="#B2E3FA" />
</shape>
</item>
</layer-list>
and layout for shape you require.
<RelativeLayout
android:id="@+id/rlv1"
android:layout_width="150dp"
android:layout_height="50dp"
android:background="@drawable/rectangle" />
<RelativeLayout
android:id="@+id/rlv2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="@+id/rlv1"
android:background="@drawable/triangle"
android:rotation="180" />
set margin according you required.
Source
Solution 2:
If you want a border for your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/text_message"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/bg_rectangle"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:padding="8dp"
android:text="Abc"
/>
<ImageView
android:id="@+id/image_arrow"
android:layout_marginTop="-1.5dp"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/icon_arrow_down"
/>
</LinearLayout>
bg_rectangle
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#eaeaea" />
<stroke
android:width="1dp"
android:color="#f00" />
<corners android:radius="8dp" />
</shape>
icon_arrow_down, or you can create triangle by vector like here
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<rotate
android:fromDegrees="45"
android:pivotX="135%"
android:pivotY="15%"
android:toDegrees="45"
>
<shape android:shape="rectangle">
<solid android:color="#eaeaea"/>
<stroke
android:width="1dp"
android:color="#f00" />
</shape>
</rotate>
</item>
</layer-list>