Android - how to define ShapeDrawables programmatically?

人盡茶涼 提交于 2019-11-27 12:05:26

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!