Changing gradient background colors on Android at runtime

前端 未结 4 1339
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 02:09

I\'m experimenting with Drawable backgrounds and have had no problems so far.

I\'m now trying to change the gradient background color at runtime.

Unfortunate

4条回答
  •  心在旅途
    2020-12-01 02:40

    Try my code below:

     int[] colors = new int[2];
                colors[0] = getRandomColor();
                colors[1] = getRandomColor();
    
    
                GradientDrawable gd = new GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM, colors);
    
                gd.setGradientType(GradientDrawable.RADIAL_GRADIENT);
                gd.setGradientRadius(300f);
                gd.setCornerRadius(0f);
                YourView.setBackground(gd);
    

    Method for generating random color:

    public static int getRandomColor(){
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(56), rnd.nextInt(256));
    }
    

提交回复
热议问题