Android - how to define ShapeDrawables programmatically?

后端 未结 2 1711
天命终不由人
天命终不由人 2020-12-02 23:32

What I\'m trying to achieve is to use a Drawable with a couple of layers inside it, but control some values at runtime such as the startColor for the gradient. Here\'s what

相关标签:
2条回答
  • 2020-12-02 23:38

    It seems that is does not work with ShapeDrawable, but take a look at my GradientDrawable example:

    GradientDrawable gd = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.RED, Color.GREEN});
    gd.setStroke(10, Color.BLUE);
    

    You may also need following method:

    gd.setGradientCenter(float x, float y);
    gd.setGradientRadius(float gradientRadius);
    
    0 讨论(0)
  • 2020-12-03 00:01

    Just gonna leave this here... Not tested yet

     /**
     * Created by Nedo on 09.04.2015.
     */
    public class ShapeBuilder {
    
        public static Drawable generateSelectorFromDrawables(Drawable pressed, Drawable normal) {
            StateListDrawable states = new StateListDrawable();
            states.addState(new int[]{ -android.R.attr.state_focused, -android.R.attr.state_pressed, -android.R.attr.state_selected}, normal);
            states.addState(new int[]{ android.R.attr.state_pressed}, pressed);
            states.addState(new int[]{ android.R.attr.state_focused}, pressed);
            states.addState(new int[]{ android.R.attr.state_selected}, pressed);
    
            return states;
        }
    
        public static Drawable generateShape(String colorTop, String colorBot, String colorStroke, int stokeSize, float strokeRadius) {
            int top, bot, stroke;
            top = Color.parseColor(colorTop);
            bot = Color.parseColor(colorBot);
            stroke = Color.parseColor(colorStroke);
    
            GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{top, bot});
            drawable.setStroke(stokeSize, stroke);
            drawable.setCornerRadius(strokeRadius);
    
            return drawable;
        }
    
        public static Drawable buildSelectorShapeFromColors(String colorNormalStroke, String colorNormalBackTop, String colorNormalBackBot,
                                                            String colorPressedStroke, String colorPressedBackTop, String colorPressedBackBot,
                                                            int strokeSize, float strokeRadius) {
    
            Drawable pressed = generateShape(colorPressedBackTop, colorPressedBackBot, colorPressedStroke, strokeSize, strokeRadius);
            Drawable normal = generateShape(colorNormalBackTop, colorNormalBackBot, colorNormalStroke, strokeSize, strokeRadius);
            return generateSelectorFromDrawables(pressed, normal);
        }
    }
    

    Edit: tested Now, had one mistake. You actually have to describe every single state. If you group states they will only be triggered if all of them accure at once...

    0 讨论(0)
提交回复
热议问题