Android 代码创建 Drawable

1、GradientDrawable
生成一个有渐变的Drawable

public static Drawable getGradientDrawable(int[] colors, int cornerRadius) 
        GradientDrawable gradientDrawableN = new GradientDrawable();
        gradientDrawableN.setCornerRadius(cornerRadius);
        gradientDrawableN.setOrientation(TL_BR);//top left to bottom right
        gradientDrawableN.setColors(colors);//colors的长度必须大于等于2
        return gradientDrawableN;
    }
 public static Drawable getDrawable(int color, int cornerRadius) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(cornerRadius);//设置4个角的弧度
        drawable.setColor(color);// 设置颜色
        return drawable;
    }

2、StateListDrawable
多状态Drawable

  public static Drawable getStateListDrawable() {
            Drawable drawable_p = getDrawable(Color.GREEN,100);//正常状态下的Drawable
            Drawable drawable_n = getDrawable(Color.RED,100);//按下和获取焦点是的Drawable
            Drawable drawable_b = getDrawable(Color.YELLOW,100);//被禁用时的Drawable
            StateListDrawable stateListDrawable = new StateListDrawable();
            stateListDrawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}, drawable_p);
            stateListDrawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, drawable_p);
            stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, drawable_n);
            stateListDrawable.addState(new int[]{-android.R.attr.state_enabled,}, drawable_b);
            stateListDrawable.addState(new int[]{-android.R.attr.state_enabled, android.R.attr.state_pressed}, drawable_b);
            stateListDrawable.addState(new int[]{-android.R.attr.state_enabled, android.R.attr.state_focused}, drawable_b);
            stateListDrawable.addState(new int[]{}, drawable_n);
            return stateListDrawable;
    }

3、LayerDrawable
多个Drawable组合成一个Drawable

 public static Drawable getLayerDrawable(int[] solidColors, int[] strokeColors, int cornerRadius, int solidWidth) {
        Drawable solidDrawable = getXSLGradientDrawable(solidColors, cornerRadius);//外层Drawable
        Drawable strokeDrawable = getXSLGradientDrawable(strokeColors, cornerRadius - (2 * solidWidth));//内层Drawable
        Drawable[] drawables = {solidDrawable, strokeDrawable};
        LayerDrawable layerDrawable = new LayerDrawable(drawables);
        layerDrawable.setLayerInset(1, solidWidth, solidWidth, solidWidth, solidWidth)
        return layerDrawable;
    }

你可能感兴趣的:(Android 代码创建 Drawable)