简体   繁体   中英

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

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM