代码设置selector

有些场景,我们需要每一个button不同的样色,而且是圆角,如果是之前,我们会设置一个selector,然后里面设置不同状态的Drawable,其中每一个drawbale都要设置圆角,这样,如果我们按钮有10个获取按钮是动态数量,这样我们不能全部配置xml。

我们可以用代码生产selector和drawable对象,把他们用代码设置为view的背景

思路,代码生产drawable对象,可以设置solid, corner, stroke等。下面,我们简单点,设置圆角,边框颜色,内容背景颜色

 int strokeWidth = 5; // 3dp 边框宽度
        int roundRadius = 15; // 8dp 圆角半径
        int strokeColor = Color.parseColor("#2E3135");//边框颜色
        int fillColor = Color.parseColor("#DFDFE0");//内部填充颜色

        //创建drawable,Android代码设置Shape,corners,Gradient
        //http://blog.csdn.net/houshunwei/article/details/17392409
        GradientDrawable gd = new GradientDrawable();
        gd.setColor(fillColor);
        gd.setCornerRadius(roundRadius);
        float r = 100f;
        gd.setCornerRadii(new float[]{r,r,r,r,r,r,r,r});
        gd.setStroke(strokeWidth, strokeColor);


        GradientDrawable gd2 = new GradientDrawable();
        gd2.setColor( Color.parseColor("#ffffff"));
        gd2.setCornerRadius(roundRadius);
        gd2.setCornerRadii(new float[]{r,r,r,r,r,r,r,r});
        gd2.setStroke(strokeWidth, strokeColor);

注意:gd.setCornerRadii(new float[]{r,r,r,r,r,r,r,r}); 这个可以设置4个角的圆角,你也可以设置其中个的几个角

然后,我们把这些drawable放到selector对象中,再把selector当做背景设置到view中

StateListDrawable drawable = new StateListDrawable();

        //Non focused states
        drawable.addState(new int[]{-android.R.attr.state_focused, -android.R.attr.state_selected, -android.R.attr.state_pressed},
                gd);
        drawable.addState(new int[]{-android.R.attr.state_focused, android.R.attr.state_selected, -android.R.attr.state_pressed},
                gd);
        //Focused states
        drawable.addState(new int[]{android.R.attr.state_focused,-android.R.attr.state_selected, -android.R.attr.state_pressed},
                gd);
        drawable.addState(new int[]{android.R.attr.state_focused,android.R.attr.state_selected, -android.R.attr.state_pressed},
                gd);
        //Pressed
        drawable.addState(new int[]{android.R.attr.state_selected, android.R.attr.state_pressed},
                gd);
        drawable.addState(new int[]{android.R.attr.state_pressed},
                gd2);
        //注意里面的“-”号,当XML的设定是false时,就需要使用资源符号的负值来设定。

        but1.setBackground(drawable);

这样,我们既可以保留圆角,又可以动态设置颜色,边框等属性。对于某种场景来说,还是挺方便。

下面是我参考的博客,这里记录一下。

http://my.oschina.net/non6/blog/298156

http://blog.csdn.net/houshunwei/article/details/17392409


效果图如下



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值