代码设置selector

来源:互联网 发布:淘宝修改密码网址 编辑:程序博客网 时间:2024/05/15 06:08

有些场景,我们需要每一个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