-
-
Save nicemak/13bc29e0714c183727f47db244d56a03 to your computer and use it in GitHub Desktop.
Example edit text with IBAN mask XXXX XXXX XXXX XXXX XXXX XXXX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.test | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.text.Editable | |
import android.text.TextWatcher | |
import com.example.test.databinding.ActivityMainBinding | |
class MainActivity : AppCompatActivity() { | |
private lateinit var binding: ActivityMainBinding | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
binding = ActivityMainBinding.inflate(layoutInflater) | |
setContentView(binding.root) | |
setUI() | |
} | |
private fun setUI() { | |
binding.editTextTest.addTextChangedListener(object : TextWatcher { | |
var _ignore = false | |
var _deletion = false | |
override fun afterTextChanged(s: Editable) { | |
if (_ignore) | |
return | |
_ignore = true | |
if (!_deletion) { | |
binding.editTextTest.setText(getFormattedIBAN(s.toString())) | |
binding.editTextTest.setSelection(binding.editTextTest.text.toString().length) | |
} | |
_ignore = false | |
} | |
override fun beforeTextChanged( | |
s: CharSequence, start: Int, | |
count: Int, after: Int | |
) { | |
_deletion = after < count | |
} | |
override fun onTextChanged( | |
s: CharSequence, start: Int, | |
before: Int, count: Int | |
) { | |
} | |
}) | |
} | |
private fun getFormattedIBAN(text: String): String { | |
val ibanMaxLength = 29 | |
if (text.length > ibanMaxLength) { | |
return text.substring(0, ibanMaxLength - 1) | |
} | |
// Delete space in bad position. | |
var result = "" | |
text.forEachIndexed { index, c -> | |
if (c.toString() == " " && (index + 1) % 5 != 0) { | |
} else { | |
result += c.toString() | |
} | |
} | |
if (result != text) { | |
return result.uppercase().trim() | |
} | |
// Add space after fourth digit | |
if (text.replace(" ", "").length % 4 == 0) { | |
return "$text ".uppercase() | |
} | |
return text.uppercase() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment