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........

3 comments:

  1. thumb is hiding at ends..setbounds also not working..give solution for this problem

    ReplyDelete
  2. Sorry for the late reply

    means your are applying gradient on the progress bar, on which thumb is getting hide at the ends, I implemented this but mine is working fine may be you need to customize the Progress bar.

    What are you trying to do? Do you want to set height and width of your Button? If so then setBounds is not to be used here. You'd need to change the Buttons LayoutParams instead.
    If I remember well, setBounds is to be used on images.

    ReplyDelete
  3. Excellent, saved me a lot of time.

    ReplyDelete