为了账号安全,请及时绑定邮箱和手机立即绑定

Android 代码实现Shape和Selector

标签:
Android

这个shape和selector,Android代码中经常用到。。。。。。

     最近的项目中写得太多,只是更换颜色而已,一个颜色又搞个xml都要呕吐,然而用颜色代替图片是正确的做法,可以有效减少占用的内存


于是乎,网上查看下资料,看看API等等,写了简单的util工具类,我个人觉得有用,因为可减少工作量

     给大伙搬个砖,写的不好,不喜勿喷。。。觉得有用的,可以根据自己项目需求更改方法即可,详情看代码

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;

/**
 * 该类是制作ShapeDrawable和代码设置selector的一个小工具类
 * 只是简单写了几个常用的,要用的时候可以复制方法改改就好
 * com.tqk.intimemodel
 * Created by ${tqk}
 * 2015/12/4.
 */
public class ShapeSelectorUtils {

    private static final String TAG = ShapeSelectorUtils.class.getSimpleName();
    /**
     * Shape is a rectangle, possibly with rounded corners
     */
    public static final int RECTANGLE = 0;

    /**
     * Shape is an ellipse
     */
    public static final int OVAL = 1;

    /**
     * Shape is a line
     */
    public static final int LINE = 2;

    /**
     * Shape is a ring.
     */
    public static final int RING = 3;

    /**
     * Gradient is linear (default.)
     */
    public static final int LINEAR_GRADIENT = 0;

    /**
     * Gradient is circular.
     */
    public static final int RADIAL_GRADIENT = 1;

    /**
     * Gradient is a sweep.
     */
    public static final int SWEEP_GRADIENT  = 2;


    private static final int DEFAULT_SHAPE = RECTANGLE;
    private static final int DEFAULT_GRADIENT = LINEAR_GRADIENT;
    private static final int DEFAULT_STROKE_WIDTH = -1;
    private static final int DEFAULT_ROUND_RADIUS  = 0;
    private static final String DEFAULT_STROKE_CORLOR  = "#dcdcdc";


    public static StateListDrawable makeSelector(Drawable normal, Drawable pressed, Drawable focused) {
        StateListDrawable bg = new StateListDrawable();
        bg.addState(new int[]{android.R.attr.state_hovered},pressed);
        bg.addState(new int[]{android.R.attr.state_selected},pressed);
        bg.addState(new int[]{android.R.attr.state_checked},pressed);
        bg.addState(new int[]{android.R.attr.state_pressed}, pressed);
        bg.addState(new int[]{android.R.attr.state_focused}, focused);
        bg.addState(new int[]{}, normal);
        return bg;
    }

    public static StateListDrawable makeSelector(Context context, int normalId, int pressedId, int focusedId) {
        StateListDrawable bg = new StateListDrawable();
        Drawable normal = context.getResources().getDrawable(normalId);
        Drawable pressed = context.getResources().getDrawable(pressedId);
        Drawable focused = context.getResources().getDrawable(focusedId);
        bg.addState(new int[]{android.R.attr.state_hovered},pressed);
        bg.addState(new int[]{android.R.attr.state_selected},pressed);
        bg.addState(new int[]{android.R.attr.state_checked},pressed);
        bg.addState(new int[]{android.R.attr.state_pressed,}, pressed);
        bg.addState(new int[]{android.R.attr.state_focused}, focused);
        bg.addState(new int[]{}, normal);
        return bg;
    }


    public static Drawable createDrawableDefault(Context context, String fillColor, int shape) {
        return createShapeDrawableByShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, DEFAULT_ROUND_RADIUS,shape);
    }

    public static Drawable createDrawableDefaultWithRadius(Context context, String fillColor, int shape,int roundRadius) {
        return createShapeDrawableByShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, roundRadius,shape);
    }

    public static Drawable createDrawableDefault(Context context, String fillColor, String strokeColor,int strokeWidth,int shape) {
        return createShapeDrawableByShape(context, fillColor, strokeColor, strokeWidth, DEFAULT_ROUND_RADIUS,shape);
    }

    public static Drawable createRectangleDefault(Context context,String fillColor) {

        return createRectangleShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, DEFAULT_ROUND_RADIUS);

    }
    public static Drawable createRectangleWithRadius(Context context,String fillColor,int roundRadius) {

        return createRectangleShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, roundRadius);

    }

    public static Drawable createRectangleShape(Context context,String fillColor,
                                                String strokeColor,int strokeWidth,
                                                int roundRadius) {
        return createShapeDrawableByShape(context, fillColor, strokeColor, strokeWidth, roundRadius, RECTANGLE);
    }


    public static Drawable createOvalDefault(Context context,String fillColor) {

        return createOvalShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, DEFAULT_ROUND_RADIUS);

    }

    public static Drawable createOvalByRadius(Context context,String fillColor,int roundRadius) {

        return createOvalShape(context, fillColor, DEFAULT_STROKE_CORLOR, DEFAULT_STROKE_WIDTH, roundRadius);

    }


    public static Drawable createOvalShape(Context context,String fillColor,
                                                String strokeColor,int strokeWidth,
                                                int roundRadius) {
        return createShapeDrawableByShape(context, fillColor, strokeColor, strokeWidth, roundRadius, OVAL);
    }


    private static Drawable createShapeDrawableByShape(Context context, String fillColor,
                                                       String strokeColor, int strokeWidth,
                                                       int roundRadius, int shape) {
        return createShapeDrawable(context, fillColor, strokeColor, strokeWidth, roundRadius, shape, LINEAR_GRADIENT);
    }

    private static Drawable createShapeDrawable(Context context,String fillColor,
                                                String strokeColor,int strokeWidth,
                                                int roundRadius, int shape,int gradient) {
        if (context == null || TextUtils.isEmpty(fillColor)) {
            return null;
        }
        if (!fillColor.startsWith("#") || !strokeColor.startsWith("#")) {
            Log.e(TAG, "Here a String color must be start with '#'");
            return null;
        }
        if (roundRadius < 0) {
            roundRadius = DEFAULT_STROKE_WIDTH;
        }
        if (shape < 0 || shape > 2) {
            shape = DEFAULT_SHAPE;
        }
        if (gradient < 0 || gradient > 2) {
            gradient = DEFAULT_GRADIENT;
        }
        if (TextUtils.isEmpty(strokeColor)) {
            strokeColor = DEFAULT_STROKE_CORLOR;
        }
        strokeWidth = dp2px(context, strokeWidth); // dp 边框宽度
        roundRadius = dp2px(context, roundRadius); // dp 圆角半径

        int sColor = Color.parseColor(strokeColor);//边框颜色
        int fColor = Color.parseColor(fillColor);//内部填充颜色

        GradientDrawable drawable = new GradientDrawable();//创建drawable

        drawable.setColor(fColor);
        drawable.setGradientType(gradient);
        drawable.setShape(shape);
        drawable.setCornerRadius(roundRadius);
        drawable.setStroke(strokeWidth, sColor);

        return drawable;
    }

    /**
     * dp转px
     *
     * @param context
     * @param dpVal
     * @return
     */
    public static int dp2px(Context context, float dpVal) {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());

    }
}
不知道怎么搞的,这个格式。。。。好吧,不熟悉,其实没什么难懂的东西,主要就是GradientDrawable这个类了,不熟悉的可以看一下源码,我也看了,有时候自己看源码比看别人对源码的解析理解更深刻一点

用法:

    给个颜色就好了,小例子:

    String []colors = new String[]{            "#d6eddc",            "#d6ede9",            "#d6e8ed",            "#d6e0ed",            "#dad6ed",            "#edd6eb",            "#edd6df",            "#eddcd6",            "#f1ebd4"    };
Drawable btDefault = ShapeSelectorUtils.createDrawableDefault(this, "#fe612a", ShapeSelectorUtils.OVAL);        Drawable btPressed = ShapeSelectorUtils.createDrawableDefault(this, colors[0], ShapeSelectorUtils.OVAL);        findViewById(R.id.button).setBackground(ShapeSelectorUtils.makeSelector(btDefault, btPressed, btPressed));        Drawable ttDefault = ShapeSelectorUtils.createRectangleWithRadius(this, colors[1],3);        Drawable ttPressed = ShapeSelectorUtils.createRectangleWithRadius(this, "#fe612a",3);        findViewById(R.id.text).setBackground(ShapeSelectorUtils.makeSelector(ttDefault, ttPressed, ttPressed));

    酱紫就不用各种写shape和selector了。。最后还是不知道格式是什么鬼,不知道怎么加个框

原文链接:http://www.apkbus.com/blog-673745-59761.html

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消