Android how to get gradient effect on setBackgroundColor

Jack BeNimble picture Jack BeNimble · May 22, 2011 · Viewed 9k times · Source

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.

Answer

nicholas.hauschild picture nicholas.hauschild · May 22, 2011

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);