Android 如何自定义EditText 下划线?

Stella981
• 阅读 826

项目要求: 笔者曾经做过一个项目,其中登录界面的交互令人印象深刻。交互设计师给出了一个非常作的设计,要求做出包含根据情况可变色的下划线,左侧有可变图标,右侧有可变删除标志的输入框,如图 Android 如何自定义EditText 下划线?

记录制作过程:

  • 第一版本

public class LineEditText extends EditText {

private Paint mPaint;
private int color;
public static final int STATUS_FOCUSED = 1;
public static final int STATUS_UNFOCUSED = 2;
public static final int STATUS_ERROR = 3;
private int status = 2;
private Drawable del_btn;
private Drawable del_btn_down;
private int focusedDrawableId = R.drawable.user_select;// 默认的
private int unfocusedDrawableId = R.drawable.user;
private int errorDrawableId = R.drawable.user_error;
Drawable left = null;
private Context mContext;

public LineEditText(Context context) {

    super(context);
    mContext = context;
    init();
}

public LineEditText(Context context, AttributeSet attrs) {

    super(context, attrs);
    mContext = context;
    init();

}

public LineEditText(Context context, AttributeSet attrs, int defStryle) {

    super(context, attrs, defStryle);
    mContext = context;
    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.lineEdittext, defStryle, 0);
    focusedDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableFocus, R.drawable.user_select);
    unfocusedDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableUnFocus, R.drawable.user);
    errorDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableError, R.drawable.user_error);
    a.recycle();
    init();
}

/** * 2014/7/31 * * @author Aimee.ZHANG */

private void init() {
    mPaint = new Paint();
    // mPaint.setStyle(Paint.Style.FILL);
    mPaint.setStrokeWidth(3.0f);
    color = Color.parseColor("#bfbfbf");
    setStatus(status);
    del_btn = mContext.getResources().getDrawable(R.drawable.del_but_bg);
    del_btn_down = mContext.getResources().getDrawable(R.drawable.del_but_bg_down);
    addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            setDrawable();
        }
    });
    setDrawable();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setColor(color);
    canvas.drawLine(0, this.getHeight() - 1, this.getWidth(),
            this.getHeight() - 1, mPaint);
}

// 删除图片
private void setDrawable() {
    if (length() < 1) {
        setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null);
    } else {
        setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn_down,null);
    }
}

// 处理删除事件
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (del_btn_down != null && event.getAction() == MotionEvent.ACTION_UP) {
        int eventX = (int) event.getRawX();
        int eventY = (int) event.getRawY();
        Log.e("eventXY", "eventX = " + eventX + "; eventY = " + eventY);  
        Rect rect = new Rect();
        getGlobalVisibleRect(rect);
        rect.left = rect.right - 50;
        if (rect.contains(eventX, eventY))
        setText("");
    }
    return super.onTouchEvent(event);
}

public void setStatus(int status) {
    this.status = status;
    

    if (status == STATUS_ERROR) {
        try {
            left = getResources().getDrawable(errorDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#f57272"));
    } else if (status == STATUS_FOCUSED) {
        try {
            left = getResources().getDrawable(focusedDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#5e99f3"));
    } else {
        try {
            left = getResources().getDrawable(unfocusedDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#bfbfbf"));
    }
    if (left != null) {

// left.setBounds(0, 0, 30, 40);

// this.setCompoundDrawables(left, null, null, null);

        setCompoundDrawablesWithIntrinsicBounds(left,null,del_btn,null);
    }
    postInvalidate();
}

public void setLeftDrawable(int focusedDrawableId, int unfocusedDrawableId,
        int errorDrawableId) {
    this.focusedDrawableId = focusedDrawableId;
    this.unfocusedDrawableId = unfocusedDrawableId;
    this.errorDrawableId = errorDrawableId;
    setStatus(status);
}

@Override
protected void onFocusChanged(boolean focused, int direction,
        Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused) {
        setStatus(STATUS_FOCUSED);
    } else {
        setStatus(STATUS_UNFOCUSED);
    }
}

@Override
protected void finalize() throws Throwable {
    super.finalize();
};

public void setColor(int color) {
    this.color = color;
    this.setTextColor(color);
    invalidate();
}

}

效果图: Android 如何自定义EditText 下划线?

代码解释:

变量名 STATUS_FOCUSED,STATUS_UNFOCUSED,STATUS_ERROR 标示了三种状态,选中状况为蓝色,未选中状态为灰色,错误状态为红色。focusedDrawableId unfocusedDrawableId errorDrawableId 存放三种状态的图片,放置于最左侧。

canvas.drawLine(0, this.getHeight() - 1, this.getWidth(),this.getHeight() - 1, mPaint); //画editText最下方的线 setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null); //放置左边的和右边的图片(左,上,右,下) 相当于 android:drawableLeft="" android:drawableRight=""

  • onTouchEvent 当手机点击时,第一个先执行的函数,当点击右侧删除图标是清空 edittext
  • setStatus 根据不同的状态,左边的图片不一样

存在的问题: 这版本虽然基本功能已经实现,但是不符合需求,设计中要求文本框中无文字时,右侧删除按钮不显示,不点击删除按钮,删除按钮要保持灰色,点击时才可以变蓝色。

因此有了第二个版本

public class LineEditText extends EditText implements TextWatcher, OnFocusChangeListener{

private Paint mPaint;
private int color;
public static final int STATUS_FOCUSED = 1;
public static final int STATUS_UNFOCUSED = 2;
public static final int STATUS_ERROR = 3;
private int status = 2;
private Drawable del_btn;
private Drawable del_btn_down;
private int focusedDrawableId = R.drawable.user_select;// 默认的
private int unfocusedDrawableId = R.drawable.user;
private int errorDrawableId = R.drawable.user_error;
Drawable left = null;
private Context mContext;
/** 
 * 是否获取焦点,默认没有焦点 
 */  
private boolean hasFocus = false;  
/** 
 * 手指抬起时的X坐标 
 */  
private int xUp = 0;  

public LineEditText(Context context) {
    super(context);
    mContext = context;
    init();
}

public LineEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    init();

}

public LineEditText(Context context, AttributeSet attrs, int defStryle) {
    super(context, attrs, defStryle);
    mContext = context;
    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.lineEdittext, defStryle, 0);
    focusedDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableFocus, R.drawable.user_select);
    unfocusedDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableUnFocus, R.drawable.user);
    errorDrawableId = a.getResourceId(
            R.styleable.lineEdittext_drawableError, R.drawable.user_error);
    a.recycle();
    init();
}

/**
 * 2014/7/31
 * 
 * @author Aimee.ZHANG
 */
private void init() {
    mPaint = new Paint();
    // mPaint.setStyle(Paint.Style.FILL);
    mPaint.setStrokeWidth(3.0f);
    color = Color.parseColor("#bfbfbf");
    setStatus(status);
    del_btn = mContext.getResources().getDrawable(R.drawable.del_but_bg);
    del_btn_down = mContext.getResources().getDrawable(R.drawable.del_but_bg_down);
    addListeners();
    setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setColor(color);
    canvas.drawLine(0, this.getHeight() - 1, this.getWidth(),
            this.getHeight() - 1, mPaint);
}

// 删除图片

// private void setDrawable() { // if (length() < 1) { // setCompoundDrawablesWithIntrinsicBounds(left, null, null, null); // } else { // setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn,null); // } // }

// 处理删除事件
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (del_btn != null && event.getAction() == MotionEvent.ACTION_UP) {
        // 获取点击时手指抬起的X坐标  
        xUp = (int) event.getX();  
        Log.e("xUp", xUp+"");  
        /*Rect rect = new Rect();
        getGlobalVisibleRect(rect);
        rect.left = rect.right - 50;*/
          // 当点击的坐标到当前输入框右侧的距离小于等于 getCompoundPaddingRight() 的距离时,则认为是点击了删除图标  
        if ((getWidth() - xUp) <= getCompoundPaddingRight()) {  
            if (!TextUtils.isEmpty(getText().toString())) {
                setText("");  
            }  
        }
    }else if(del_btn != null && event.getAction() == MotionEvent.ACTION_DOWN && getText().length()!=0){
        setCompoundDrawablesWithIntrinsicBounds(left,null,del_btn_down,null);
    }else if(getText().length()!=0){
        setCompoundDrawablesWithIntrinsicBounds(left,null,del_btn,null);
    }
    return super.onTouchEvent(event);
}

public void setStatus(int status) {
    this.status = status;
    

    if (status == STATUS_ERROR) {
        try {
            left = getResources().getDrawable(errorDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#f57272"));
    } else if (status == STATUS_FOCUSED) {
        try {
            left = getResources().getDrawable(focusedDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#5e99f3"));
    } else {
        try {
            left = getResources().getDrawable(unfocusedDrawableId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        setColor(Color.parseColor("#bfbfbf"));
    }
    if (left != null) {

// left.setBounds(0, 0, 30, 40); // this.setCompoundDrawables(left, null, null, null); setCompoundDrawablesWithIntrinsicBounds(left,null,null,null); } postInvalidate(); }

public void setLeftDrawable(int focusedDrawableId, int unfocusedDrawableId,
        int errorDrawableId) {
    this.focusedDrawableId = focusedDrawableId;
    this.unfocusedDrawableId = unfocusedDrawableId;
    this.errorDrawableId = errorDrawableId;
    setStatus(status);
}
 private void addListeners() {  
        try {  
            setOnFocusChangeListener(this);  
            addTextChangedListener(this);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
@Override
protected void onFocusChanged(boolean focused, int direction,
        Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    this.hasFocus=focused;
    if (focused) {
        setStatus(STATUS_FOCUSED);
    } else {
        setStatus(STATUS_UNFOCUSED);
        setCompoundDrawablesWithIntrinsicBounds(left,null,null,null);
    }
}

@Override
protected void finalize() throws Throwable {
    super.finalize();
};

public void setColor(int color) {
    this.color = color;
    this.setTextColor(color);
    invalidate();
}



@Override
public void afterTextChanged(Editable arg0) {
    // TODO Auto-generated method stub
    postInvalidate();
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
        int arg3) {
    // TODO Auto-generated method stub
     if (TextUtils.isEmpty(arg0)) {  
         // 如果为空,则不显示删除图标  
         setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);  
     } else {  
         // 如果非空,则要显示删除图标  
         setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null);  
     }  
}
@Override
 public void onTextChanged(CharSequence s, int start, int before, int after) {  
   if (hasFocus) {  
       if (TextUtils.isEmpty(s)) {  
           // 如果为空,则不显示删除图标  
           setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);  
       } else {  
           // 如果非空,则要显示删除图标  
           setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null);  
       }  
   }  

}

@Override
public void onFocusChange(View arg0, boolean arg1) {
    // TODO Auto-generated method stub
    try {  
        this.hasFocus = arg1;  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

}

比较关键的方法是:onTouchEvent

当进入界面,点击输入框,要判断输入框中是否已有文字,如果有则显示灰色的删除按钮,如果没有则不显示,如果点击了删除按钮,删除按钮变蓝色

存在的问题: 这个版本依旧存在问题,就是输入长度超过输入框,所画的线不会延伸,如图

Android 如何自定义EditText 下划线?

解决方法:

@Override

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setColor(color);
    int x=this.getScrollX();
    int w=this.getMeasuredWidth();
    canvas.drawLine(0, this.getHeight() - 1, w+x,
            this.getHeight() - 1, mPaint);
}

w:获取控件长度

X:延伸后的长度

最终效果: Android 如何自定义EditText 下划线?

在分享完这个界面的代码设计后,笔者跟大家唠一些新玩意。话说身处在帝都,如果不利用好帝都的丰厚资源,又如何对得起每天吸入的几十斤雾霾?

话唠的分享

在帝都生活,我每天早晨起来都会告诉自己,又是新的一天,要认真过。

写一个 APP 很容易,写好一个 APP 很难。如何检验自己所写的 APP 的性能状况,用户体验?

什么是 APM?

In the fields of information technology and systems management, Application Performance Management (APM) is the monitoring and management of performance and availability of software applications. APM strives to detect and diagnose complex application performance problems to maintain an expected level of service. APM is "the translation of IT metrics into business meaning .

国内外有已很多成熟的 APM 厂商,笔者也曾染指过几家,如AppDynamics,Newrelic,OneAPM

还有专注于 APP 崩溃监控的产品:Crashlytics,Crittercism,Bugly等

今天我想给大家分享的是从OneAPM Mobile Insight 产品中发现的一块新大陆--卡顿监控

对流畅度的概念,相信大家并不陌生,即 1s 中之内绘图刷新信号中断的次数。流畅度次数越接近 40 时,用户能感知到卡顿,流畅度在 20以下卡顿比较严重。OneAPM Mobile Insight的卡顿监控就是一个监控流畅度指标的模块。

Android 如何自定义EditText 下划线?

  • 卡顿趋势图:随时间的推移,反馈卡顿发生次数的趋势情况
  • 设备分布图:卡顿现象集中分布的设备类型
  • 卡顿页面:发生卡顿的页面有哪些,其中平均流畅度是多少,卡顿了多少次等信息。

Android 如何自定义EditText 下划线?

Android 如何自定义EditText 下划线?

查看单个页面的卡顿情况,并从页面线程加载的情况中分析造成卡顿原因

如果你也想检验一下自己所写的 APP 的用户体验情况,不妨试试这个新玩意~~

OneAPM Mobile Insight 以真实用户体验为度量标准进行 Crash 分析,监控网络请求及网络错误,提升用户留存。访问 OneAPM 官方网站感受更多应用性能优化体验,想阅读更多技术文章,请访问 OneAPM 官方技术博客

本文转自 OneAPM 官方博客

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Peter20 Peter20
3年前
mysql中like用法
like的通配符有两种%(百分号):代表零个、一个或者多个字符。\(下划线):代表一个数字或者字符。1\.name以"李"开头wherenamelike'李%'2\.name中包含"云",“云”可以在任何位置wherenamelike'%云%'3\.第二个和第三个字符是0的值wheresalarylike'\00%'4\
Stella981 Stella981
3年前
AndroidStudio封装SDK的那些事
<divclass"markdown\_views"<!flowchart箭头图标勿删<svgxmlns"http://www.w3.org/2000/svg"style"display:none;"<pathstrokelinecap"round"d"M5,00,2.55,5z"id"raphael
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Stella981 Stella981
3年前
Android 重写EditText自定义密码输入框
首先看看效果!(https://static.oschina.net/uploads/space/2016/1215/173118_LdXU_2275240.png)如上图的密码输入框,没有密码时,有几个密码就有几条下划线,输入密码后显示的内容为“\”,并且底部就没有下划线了,同样有很多方式实现,这里就偷懒改改EditText来实现,所以需要做
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这