Friday, April 23, 2010

Creating backgrounds: it's easy (part 1)

During developing UI applications for Android, you often have to work with images: icons, backgrounds and others. If you need icon, you (or your designer) paint it using some image editor, like PhotoShop. But what should you do when it needs to create just a simple background for your widget? Install an image editor, research that, and then create background? - Too many actions for creating a simple background.

Android SDK provides a set of easy ways to define backgrounds, and one of them is the shape drawable XML element. For instance, here is a rounded green drawable:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    
<solid android:color="#FF00FF00"/>
    
<corners android:radius="8dp" />
</shape>

Let create a simple rounded App widget that has an icon and text with a transparent background:


It changes own view on selecting and pressing, like a lot of Android widgets (icons on Home, buttons etc.):

State Selected

State Pressed


Here is the background drawable of App widget:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    
<item android:state_window_focused="false" android:drawable="@drawable/bg_normal" />
    
<item android:state_pressed="true" android:drawable="@drawable/bg_pressed" />
    
<item android:state_focused="true" android:drawable="@drawable/bg_selected" />
    
<item android:drawable="@drawable/bg_normal" />
</selector>

Normal background (bg_normal.xml) has transparent color and rounded corners:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    
<solid android:color="#AA111111"/>
    
<padding android:left="6dp" android:top="6dp"
         android:right
="6dp" android:bottom="6dp" />
    
<corners android:radius="8dp" />
</shape>


Selected (bg_selected.xml) and Pressed (bg_pressed.xml) backgrounds extend Normal background by adding border and changing background color. They look alike, just have different border colors (#FFEEC000 - for pressed, #FFFF8000 - for selected):

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    
<solid android:color="#A777"/>
    
<padding android:left="6dp" android:top="6dp"
         android:right
="6dp" android:bottom="6dp" />
    
<corners android:radius="8dp" />
    
<stroke android:width="4dip" android:color="#FFFF8000" />
</shape>

1 comment:

  1. On selected and pressed events, there is no change in display..please help me..

    ReplyDelete