如何通过代码创建shape, 创建layer-list

实例一

通过代码创建渐变颜色的shape

GradientDrawable shape = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, bgColor);//设置渐变从左到右
shape.setShape(GradientDrawable.RECTANGLE);//设置为矩形
shape.setCornerRadius(radius);//设置圆角

一个相对复杂的demo

比如模仿ios的onOffButton,但是产品经理要求改变选中时候的颜色,本来我们是用图片做的,现在只好用shap自己画了。
比如下图:


如何通过代码创建shape, 创建layer-list_第1张图片

通过xml来做

bg_switch_on.xml



    
        
            
            
            
                
                
        

    
    
        
            
            
        
    

bg_switch_off.xml



    
        
            
            
        

    
    
        
            
            
        
    

selector_switch.xml



    
    

在style中添加button的style

    

在toogleButton中引用:


这样就可以成功改变toogleButton按钮的样式了,但是过于麻烦了,也可以直接使用Android本身自带的Switch,Switch还是很好看的。

而且这种方式有一个问题是长度和高度要成比例,不然很难看。

通过代码实现这个layer-list

我们也可以通过代码把上面的layer-list写出来:

    public static StateListDrawable genOnoffButtonSelector(int color, Context context) {
        StateListDrawable res = new StateListDrawable();
        res.addState(new int[]{android.R.attr.state_checked}, genCheckedDrawable(color));
        res.addState(new int[]{}, context.getResources().getDrawable(R.drawable.atom_flight_toggle_btn_unchecked));
        return res;
    }

    public static Drawable genCheckedDrawable(int color) {
        GradientDrawable roundRect = new GradientDrawable();
        roundRect.setShape(GradientDrawable.RECTANGLE);
        roundRect.setSize(BitmapHelper.dip2px(52), BitmapHelper.dip2px(30));
        roundRect.setCornerRadius(BitmapHelper.dip2px(16));
        roundRect.setColor(color);
        GradientDrawable circle = new GradientDrawable();
        circle.setShape(GradientDrawable.OVAL);
        circle.setSize(BitmapHelper.dip2px(24), BitmapHelper.dip2px(24));
        circle.setColor(Color.parseColor("#ffffff"));
        InsetDrawable insetLayer2 = new InsetDrawable(circle, BitmapHelper.dip2px(23), 4, 3, 4);
        return new LayerDrawable(new Drawable[]{roundRect, insetLayer2});
    }

这里第二个,没有点击的状态是一张图片,因为设计师说那个有阴影效果我画不出来,所以就直接用的图片,如果想要做也是一样的。

你可能感兴趣的:(如何通过代码创建shape, 创建layer-list)