EditText动态内容监听

作者 Lin Wait For Li 日期 2016-11-06
EditText动态内容监听

最近在做一个项目过程中需要一种能提醒用户还能输入多少个字体的EditText,因为在直接用getText().length()时候出现输入一个字体时候还是显示0,所以想把自己实现的功能代码写下来可以以后用上:

初步了解addTextChangedListener方法

  1. public void beforeTextChanged(CharSequence s, int start, int count, int after)
    这个方法是在EditText内容改变之前调用的方法.

  2. public void onTextChanged(CharSequence s, int start, int before, int count)
    这个方法是在EditText内容改变过程中调用的方法.

  3. public void afterTextChanged(Editable s) :
    这个方法是在EdiTText内容改变完成后调用的.

深入了解addTextChangedListener里面的属性

深入了解beforeTextChanged方法参数

public void beforeTextChanged(CharSequence s, int start, int count, int after)有start属性、count属性、after属性。

  1. 其中start属性是变化前内容的个数。但是对于你增加一个数字来说start属性代表着没输入新内容的个数;对于减法而言start属性代表着你已经删除字体后内容的个数
  2. count属性是你按×删除掉内容字体的个数.
  3. after属性是新增加内容的个体数.

深入了解onTextChanged方法参数

public void onTextChanged(CharSequence s, int start, int before, int count)中有start属性、before属性、count属性。

  1. 其中start属性是变化前内容的个数。但是对于你增加一个数字来说start属性代表着没输入新内容的个数;对于减法而言start属性代表着你已经删除字体后内容的个数
  2. count属性是是增加内容后的个数与增加内容钱的个数的差值.
  3. before属性是删除内容前的个数与删除后内容后的个数的差值.

话不多说,直接上实现功能的代码:

private int txt_content = 0;//先声明一个变量记录输入的内容个数
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
txt_content = start + after;//获取内容变化前总体内容个数
if(input_length >= 0){
input_length = MAX_INPUT - txt_content;
}
LogUtils.i(getClass().getName(),"beforeTextChanged="+start+",after="+after+",count="+count);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(count != 0){
txt_content = count + txt_content;
}
if(before != 0){
txt_content = txt_content - before;
}
}
@Override
public void afterTextChanged(Editable s) {
txt_input_number.setText(input_length+"/140");
}
});

最后你还需要在EdiTText的xml属性中添加android:maxLength=”MAX_Input”,这样就大功告成了。

效果图

  1. 没有输入任何内容之前:
    edit_one

  2. 输入内容以后:
    edit_two

  3. 删除内容后:
    edit_third