SoFunction
Updated on 2025-04-12

Android Shape control beautification implementation code

If you are not satisfied with the UI controls that come with Android system, you can try custom controls. Let's take Button as an example. A long time ago, Android 123 wrote about the Android Button button control beautification method mentioned the xml selector structure. Of course, in addition to using pictures like drawable today, Android Development Network will discuss the method of custom graphics shape.For Button controls, the following attributes are supported on Android.

Let’s take the current system’s Button selector as an example:

 <shape>
  <gradient
  android:startColor="#ff8c00"
  android:endColor="#FFFFFF"
  android:angle="270" />
  <stroke
  android:width="2dp"
  android:color="#dcdcdc" />
  <corners
  android:radius="2dp" />
  <padding
  android:left="10dp"
  android:top="10dp"
  android:right="10dp"
  android:bottom="10dp" />
 </shape>

For the above, the definitions of this shape are gradients. In the gradient, the startColor attribute is the color at the beginning, the endColor is the color at the end, and the angle below is the angle. Next is the stroke that can be understood as the edge, corners are corners, where the radius attribute is the radius, and finally the relative position attribute padding.

The complete definition of a Button can be

 <?xml version="1.0" encoding="utf-8"?>
<selector
 xmlns:andro>
 <item android:state_pressed="true" >
 <shape>
  <gradient
  android:startColor="#ff8c00"
  android:endColor="#FFFFFF"
  android:angle="270" />
  <stroke
  android:width="2dp"
  android:color="#dcdcdc" />
  <corners
  android:radius="2dp" />
  <padding
  android:left="10dp"
  android:top="10dp"
  android:right="10dp"
  android:bottom="10dp" />
 </shape>
 </item>
 <item android:state_focused="true" >
 <shape>
  <gradient
  android:startColor="#ffc2b7"
  android:endColor="#ffc2b7"
  android:angle="270" />
  <stroke
  android:width="2dp"
  android:color="#dcdcdc" />
  <corners
  android:radius="2dp" />
  <padding
  android:left="10dp"
  android:top="10dp"
  android:right="10dp"
  android:bottom="10dp" />
 </shape>
 </item>
 <item> 
 <shape>
  <gradient
  android:startColor="#ff9d77"
  android:endColor="#ff9d77"
  android:angle="270" />
  <stroke
  android:width="2dp"
  android:color="#fad3cf" />
  <corners
  android:radius="2dp" />
  <padding
  android:left="10dp"
  android:top="10dp"
  android:right="10dp"
  android:bottom="10dp" />
 </shape>
 </item>
</selector>

Note that Android 123 prompts you that the difference between the above items is mainly reflected in the fact that when state_pressed or state_focused gets focus, it is time to determine what type is displayed, and items without state_xxx attribute can be regarded as normal.

The above is a compilation of Android control beautification Shape information, for reference by students in need.