美文网首页Android开发经验谈Android开发半栈工程师
Android全代码封装按压效果(可设圆角)

Android全代码封装按压效果(可设圆角)

作者: 黄油伯伯 | 来源:发表于2017-10-19 11:00 被阅读162次
    前言

    安卓的按压效果的传统方式是shape.xml文件,不过如果当项目比较多按钮都需要自定义按压效果的话,shape.xml的数量可是非常头疼的(即使是ctrl c+ ctrlv),故此可以采用动态方式进行按压效果的实现。

    上代码

    /**
    * 
    * @param RADIUS
    *            角度
    * @param normalFileName
    *            正常颜色
    * @param pressFileName
    *            点击颜色
    * @param type
    *            -1:left 0:center 1:right 2:四角圆角
    * @return
    */
    public static StateListDrawable addDrawable(int RADIUS, int normalFileName,
    int pressFileName, int type) {
    StateListDrawable sd = new StateListDrawable();
    
    
    if (RADIUS != 0) {
    float[] float1 = null;
    
    
    if (type == -1) {
    float1 = new float[] { 0, 0, 0, 0, 0, 0, RADIUS, RADIUS };
    
    
    } else if (type == 0) {
    float1 = new float[] { 0, 0, 0, 0, 0, 0, 0, 0 };
    
    
    } else if (type == 1) {
    float1 = new float[] { 0, 0, 0, 0, RADIUS, RADIUS, 0, 0 };
    
    
    } else if (type == 2) { // 设置四个角为圆角
    float1 = new float[] { RADIUS, RADIUS, RADIUS, RADIUS, RADIUS,
    RADIUS, RADIUS, RADIUS };
    
    
    } else {
    float1 = new float[] { 0, 0, 0, 0, RADIUS, RADIUS, RADIUS,
    RADIUS };
    }
    
    
    GradientDrawable gd = new GradientDrawable();
    gd.setCornerRadii(float1);
    gd.setColor(normalFileName);
    GradientDrawable gd2 = new GradientDrawable();
    gd2.setCornerRadii(float1);
    gd2.setColor(pressFileName);
    
    
    int pressed = android.R.attr.state_pressed;
    int window_focused = android.R.attr.state_window_focused;
    int focused = android.R.attr.state_focused;
    int selected = android.R.attr.state_selected;
    sd.addState(new int[] { pressed, window_focused }, gd2);
    sd.addState(new int[] { pressed, -focused }, gd2);
    sd.addState(new int[] { selected }, gd2);
    sd.addState(new int[] { focused }, gd2);
    sd.addState(new int[] {}, gd);
    return sd;
    
    
    } else {
    GradientDrawable gd = new GradientDrawable();
    gd.setColor(normalFileName);
    GradientDrawable gd2 = new GradientDrawable();
    gd2.setColor(pressFileName);
    int pressed = android.R.attr.state_pressed;
    int window_focused = android.R.attr.state_window_focused;
    int focused = android.R.attr.state_focused;
    int selected = android.R.attr.state_selected;
    sd.addState(new int[] { pressed, window_focused }, gd2);
    sd.addState(new int[] { pressed, -focused }, gd2);
    sd.addState(new int[] { selected }, gd2);
    sd.addState(new int[] { focused }, gd2);
    sd.addState(new int[] {}, gd);
    return sd;
    }
    
    
    }
    
    小结

    小建议,建一个获取不同按压效果的管理类,这样就可以统一入口替换资源图片了。欢迎各位大神有更好的做法分享到评论区~

    相关文章

      网友评论

        本文标题:Android全代码封装按压效果(可设圆角)

        本文链接:https://www.haomeiwen.com/subject/ivhuuxtx.html