beachboy2009
beachboy2009

Reputation: 5

How can I programmatically create a shape in Android

I have following myRec.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <corners android:radius="1dp"
                android:bottomRightRadius="0dp"
                android:bottomLeftRadius="4dp"
                android:topLeftRadius="4dp"
                android:topRightRadius="0dp"/>
            <stroke 
                android:color="@color/my_button_border"
                android:width="1dp" />
            <solid android:color="@android:color/transparent" />
        </shape>
     </item>
</selector>

.... and would like to create the same shape programmatically so that I can freely change color in runtime. How can I achieve it? Much thanks in advance

Upvotes: 0

Views: 959

Answers (2)

Carlos Robles
Carlos Robles

Reputation: 10947

Take a look at the android.graphics.drawable.ShapeDrawable class and the Shape class subclasses, suchs as:

  • PathShape
  • RectShape
  • ArcShape
  • OvalShape
  • RoundRectShape

ShapeDrawable receives a shape in the constructor, and then you have a lot of function to modify the shape. Also, you can retrieve the Paint asociated to the ShapeDrawable so you can alter things like the color and so.

Also, take a look at this small example:

http://www.edumobile.org/android/android-tutorial/shape-drawing-example-in-android/

where you can see some diferent shapes, and some efects suchs as the CornerPathEffect,

Upvotes: 1

Pulkit Sethi
Pulkit Sethi

Reputation: 1325

Use shapedrawable, gradientdrawable with

http://developer.android.com/reference/android/graphics/CornerPathEffect.html

Upvotes: 0

Related Questions