4

Is there a way to get a gradient effect or a semi-transparant effect when setting the background color of a view? For example, this code:

selView.setBackgroundColor(Color.rgb(240, 128, 128)); // light red

highlights a selected view in a list view. Either a gradient or a background would be cool.

Jack BeNimble
  • 35,733
  • 41
  • 130
  • 213

3 Answers3

14

You would first need to create a gradient in xml.

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
  android:shape="rectangle"> 
  <gradient 
  android:startColor="#FFFF00FF" 
  android:endColor="#FFFFFFFF" 
  android:angle="270"/> 
</shape>

You should add this to one of your drawables.xml. You should then be able to apply this to your ListView in xml.

android:background=@drawable/yourdrawable

or

setBackgroundResource(R.drawable.yourdrawable);
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
  • Thanks for the answer. I wasn't able to use it because with the the color turned out to be a bit too dark for my application. I'm not sure it will work, because even with a color change it appeared the same. – Jack BeNimble May 23 '11 at 20:42
  • Did you attempt to rebuild/clean the project after you changed your gradient definition? – nicholas.hauschild May 23 '11 at 21:18
  • Ok, the problem was that I needed to use setBackgroundResource - now it works like a charm. Thanks! – Jack BeNimble May 23 '11 at 23:47
8

i will give you a sample code

  <item android:state_pressed="true" >
    <shape>
    <gradient
    android:startColor="#ff5500"
    android:endColor="#999999"
    android:angle="270" />
    <stroke
    android:width="3dp"
    android:color="#999999" />
    <corners
    android:radius="3dp" />
    <padding
    android:left="10dp"
    android:top="10dp"
    android:right="10dp"
    android:bottom="10dp" />
    </shape>
    </item>

    <item android:state_focused="true" >
    <shape>
    <gradient
    android:endColor="#ff5500"
    android:startColor="#999999"
    android:angle="270" />
    <stroke
    android:width="3dp"
    android:color="#999999" />
    <corners
    android:radius="3dp" />
    <padding
    android:left="10dp"
    android:top="10dp"
    android:right="10dp"
    android:bottom="10dp" />
    </shape>
    </item>

    <item> 
    <shape 
    android:shape="rectangle">

    <gradient android:type="radial" android:gradientRadius="50"
    android:startColor="#999999" android:endColor="#000000" />
    <!-- <corners-->
    <!-- android:radius="10dp" />-->
    <corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
    android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
    </shape>
    </item>
    </selector>

apply this to your view from drawable

Sreedev
  • 6,563
  • 5
  • 43
  • 66
-1
setBackgroundDrawable(R.drawable.my_fancy_gradient_or_picture)
vt.
  • 1,073
  • 8
  • 12