重写 AppCompatEditText ,实现 以 3 个文字中间使用空格分离

  • 若需要分割符,把空格替换即可
  • 若需要多个文字中间分割的话,把对 3 取余 换下即可。
class AppCompatThreeSpaceEditText : AppCompatEditText {    var trueText: String = ""    private var isRun: Boolean = false    private val threeSpaceEdit = this    constructor(cxt: Context) : super(cxt) {        setOnChangeClick()    }    constructor(cxt: Context, attributes: AttributeSet) : super(cxt, attributes) {        setOnChangeClick()    }    constructor(cxt: Context, attributes: AttributeSet, defStyleAttr: Int) : super(cxt, attributes, defStyleAttr) {        setOnChangeClick()    }    private fun setOnChangeClick() {        threeSpaceEdit.addTextChangedListener(object : TextWatcher {           private var changeBeforeLength: Int = 0            override fun afterTextChanged(s: Editable?) {            }            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {                if (s == null) {                    return                }                changeBeforeLength = s.length            }            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {                if (s == null) {                    return                }                if (isRun) {                    isRun = false                    return                }                isRun = true                val buffer: java.lang.StringBuffer = java.lang.StringBuffer()                trueText = s.toString().replace(" ", "")                if (changeBeforeLength > s.length) {                    // 删除内容                    buffer.append(s.toString())                } else {                    // 真实输入文字的长度                    val length = trueText.length                    for (index in 1..length) {                        buffer.append(trueText[index - 1])                        if (index % 3 == 0) {                            buffer.append(" ")                        }                    }                }                threeSpaceEdit.setText(buffer.toString())                threeSpaceEdit.setSelection(buffer.length)                // LogUtil.v("$trueText")            }        })    }}

示例:

更多相关文章

  1. Android集成融云IM踩坑记录
  2. UBUNTU 10.10 编译Android(安卓)2.3.1源码以及SDK
  3. Android(安卓)程序奔溃常见问题汇总
  4. Ubuntu安装android源码编译工具
  5. 一分钟解决Shape分割线及分割线圆角框
  6. RecyclerView 的分割线(divider)--DividerItemDecoration
  7. 发送短信之分割短信 SMSManager
  8. android recycler添加分割线 点击事件等
  9. Android如何快速实现打渠道打包

随机推荐

  1. 0701作业
  2. 固定导航栏
  3. 【阿里云镜像】使用阿里巴巴开源镜像站镜
  4. 聊一聊如何把SSL证书安装到小鸟云服务器
  5. 服务器登录密码忘记了怎么办?总结办法如下
  6. 阿萨德请问日期为人
  7. 飞舞的气泡
  8. 对容器镜像的思考和讨论
  9. 对象模拟数组
  10. Java基于NIO实现聊天室功能