How to mask an EditText to show the dd/mm/yyyy date format

后端 未结 9 2456
甜味超标
甜味超标 2020-11-30 18:31

How can I format an EditText to follow the \"dd/mm/yyyy\" format the same way that we can format using a TextWatcher to mask

9条回答
  •  猫巷女王i
    2020-11-30 19:17

    The current answer is very good and helped guide me towards my own solution. There are a few reasons why I decided to post my own solution even though this question already has a valid answer:

    • I´m working in Kotlin, not Java. People who find themselves with the same issue will have to translate the current solution.
    • I wanted to write an answer that was more legible so that people can more easily adapt it to their own problems.
    • As suggested by dengue8830, I encapsulated the solution to this problem in a class, so anyone can use without even worrying about the implementation.

    To use it, just do something like:

    • DateInputMask(mEditText).listen()

    And the solution is shown below:

    class DateInputMask(val input : EditText) {
    
        fun listen() {
            input.addTextChangedListener(mDateEntryWatcher)
        }
    
        private val mDateEntryWatcher = object : TextWatcher {
    
            var edited = false
            val dividerCharacter = "/"
    
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (edited) {
                    edited = false
                    return
                }
    
                var working = getEditText()
    
                working = manageDateDivider(working, 2, start, before)
                working = manageDateDivider(working, 5, start, before)
    
                edited = true
                input.setText(working)
                input.setSelection(input.text.length)
            }
    
            private fun manageDateDivider(working: String, position : Int, start: Int, before: Int) : String{
                if (working.length == position) {
                    return if (before <= position && start < position)
                        working + dividerCharacter
                    else
                        working.dropLast(1)
                }
                return working
            }
    
            private fun getEditText() : String {
                return if (input.text.length >= 10)
                    input.text.toString().substring(0,10)
                else
                    input.text.toString()
            }
    
            override fun afterTextChanged(s: Editable) {}
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        }
    }
    

提交回复
热议问题