版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34900897/article/details/83537351
虽然百度上面有很多方法,但是为了更加记忆深刻,自己还是整理一遍。
etAmount?.addTextChangedListener(object :TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
}
})
一般都要实现这个方法,这里提供两种方法,就因为这个也花了几个小时的时间,,充分的说明还是只是储备不够啊
1.替换方法
override fun afterTextChanged(s: Editable?) {
val tes = s.toString().trim()
val len = tes.length
if (len >1 && tes.startsWith("0")){
s?.replace(0,1,"")
}
}
之前一直把这个用在onTextchanged方法里面,,导致一直报错,因为onTextchanged里面还有一些逻辑处理,所以导致报错,不知道没有那个逻辑处理,放在ontextchanged会不会出现问题,待后面有时间再做处理。其实replace在afterTextChanged和在ontextchanged方法是不一样的
afterTextChange方法里面的replace在Editable里面
/**
* Convenience for replace(st, en, text, 0, text.length())
* @see #replace(int, int, CharSequence, int, int)
*/
public Editable replace(int st, int en, CharSequence text);
有三个参数
1.st 开始
2.en结束
3.test需要替换的参数
在onChanged里面的replace 在Strings类里面
/**
* Returns a new string obtained by replacing each substring of this char sequence that matches the given regular expression
* with the given [replacement].
*
* The [replacement] can consist of any combination of literal text and $-substitutions. To treat the replacement string
* literally escape it with the [kotlin.text.Regex.Companion.escapeReplacement] method.
*/
@kotlin.internal.InlineOnly
public inline fun CharSequence.replace(regex: Regex, replacement: String): String = regex.replace(this, replacement)
这里需要自己去翻译过来看
2.删除方法
string类里面没有delete方法,在Editable里面才有delete方法
/**
* Convenience for replace(st, en, "", 0, 0)
* @see #replace(int, int, CharSequence, int, int)
*/
public Editable delete(int st, int en);
实现效果和replace差不多
override fun afterTextChanged(s: Editable?) {
val tes = s.toString().trim()
val len = tes.length
if (len >1 && tes.startsWith("0")){
s?.delete(0,1)
}
}
从0开始删除,保留后面