Friday, May 13, 2011

Android Programmatically create a gradient view



Here are some views which I have customized via shader and shapedrawable class. We can create more style via this code on changing shape and Shader.TileMode.MIRROR. I have attached eclipse running code at last.

View view= findViewById(R.id.anyViewLayout);

 int[] gradientColors = new int[2];
// http://developer.android.com/reference/android/graphics/Color.html
//Color.argb(Alpha, Red, Green, Blue) ;
 gradientColors [0] = Color.argb( 255, 198, 194, 194);
 gradientColors [1] = Color.argb( 255,  50, 50, 50);
createGradientBackground(view, gradientColors );// method which will draw a gradient for your view u can pass  any view to this method either button or any layout.

     
//method for creating gradient background
      private void createGradientBackground(View view, int[] gradientColors){

//Android View. setPadding(int left, int top, int right, int bottom) only accepts values in px
for more go to here .
          view.setPadding(7, 3, 7, 5);               
          final Shader upperShader = new LinearGradient(0, 0, 0, 40, gradientColors[0], gradientColors[1], Shader.TileMode.MIRROR);   shader
       
 float[] roundedCorner = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };// used for rounding the view either button or any layout
            
         
          ShapeDrawable normal = new ShapeDrawable(new RoundRectShape(roundedCorner, null, null));
          normal.getPaint().setShader(upperShader);
         
//          final Shader lowerShader = new LinearGradient (0, 0, 0,30, new int[] {  0x55FFFFFF, 0x22FFFFFF}, null, TileMode.CLAMP);
//          normal.getPaint().setShader(lowerShader);
         
          normal.setPadding(7, 3, 7, 5);
          // Create a state list (I suppressed settings for pressed).
          StateListDrawable stateList = new StateListDrawable();
          stateList.addState(new int[] { }, normal);
          view.setBackgroundDrawable(stateList);
       }
You can download eclipse project from here

Feel free to comment........