Advertisement
AntonioVillanueva

TextWatcher modelo IP en kotlin

Dec 14th, 2021
1,213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.29 KB | None | 0 0
  1. package com.example.testtextwatcher
  2.  
  3. import androidx.appcompat.app.AppCompatActivity
  4. import android.os.Bundle
  5. import com.example.testtextwatcher.databinding.ActivityMainBinding
  6. import android.text.TextWatcher
  7. import android.text.Editable
  8. import android.view.View.OnFocusChangeListener
  9.  
  10. class MainActivity : AppCompatActivity() {
  11.     private lateinit var binding: ActivityMainBinding
  12.  
  13.     override fun onCreate(savedInstanceState: Bundle?) {
  14.         super.onCreate(savedInstanceState)
  15.         binding = ActivityMainBinding.inflate(layoutInflater)
  16.  
  17.         val view = binding.root
  18.         setContentView(view)
  19.        
  20.         var entrada =binding.editTextNumberDecimal
  21.         var salida=binding.textView
  22.        
  23.         //texto.setText("algo") //Escritura en el EditText
  24.  
  25.         //TestWatcher A
  26.         //Anado un Textwatcher a la entrada que es un "EditText"
  27.  
  28.         entrada.addTextChangedListener(object : TextWatcher {
  29.  
  30.             var antiguo="" //Texto en el EditText antes de modificar ..
  31.  
  32.             //Despues de cambiar el texto decimal mira si es inferior a 255
  33.             override fun afterTextChanged(s: Editable) {
  34.                 if (s.toString().isNotEmpty()) { //Si la cadena no esta vacia
  35.                     if (s.toString().toInt() > 255) { //Si es mayor a 255
  36.                         entrada.setText("0")//La seteas a 0
  37.                     }
  38.                 }
  39.             }
  40.  
  41.             //Recupera el texto antes de modificar y lo guarda en la variable local antiguo
  42.             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
  43.                 antiguo=s.toString() //Recupera el texto antes de ser modificado
  44.             }
  45.  
  46.             //Cada vez que modifico el texto
  47.             override fun onTextChanged(s: CharSequence, start: Int,before: Int, count: Int) {
  48.                 //Cuando el texto cambia afecto un textView de salida
  49.                 salida.setText("Texto en el EditText : " + s) //debug
  50.                
  51.                 //Limita a 3 caracteres la entrada de texto
  52.                 if ((s.toString().isNotEmpty()) and  (s.toString().length > 3)){ //Limita a 3 caracteres
  53.                     entrada.setText(antiguo.substring(0,3))
  54.                 }
  55.             }
  56.         })
  57.        
  58.         //TestWatcher B
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement