2021年3月29日月曜日

改行を入力させない EditText 用 InputFilter

  1. class MainActivity : AppCompatActivity() {  
  2.   
  3.     override fun onCreate(savedInstanceState: Bundle?) {  
  4.         super.onCreate(savedInstanceState)  
  5.         setContentView(R.layout.activity_main)  
  6.   
  7.         val editText = findViewById<EditText>(R.id.editText)  
  8.         editText.filters = editText.filters + MyInputFilter()  
  9.     }  
  10. }  
  11.   
  12. class MyInputFilter : InputFilter {  
  13.   
  14.     override fun filter(  
  15.         source: CharSequence,  
  16.         start: Int,  
  17.         end: Int,  
  18.         dest: Spanned,  
  19.         dstart: Int,  
  20.         dend: Int  
  21.     ): CharSequence? {  
  22.   
  23.         var i: Int = start  
  24.         while (i < end) {  
  25.             if (source[i] == '\n') {  
  26.                 break  
  27.             }  
  28.             i++  
  29.         }  
  30.   
  31.         if (i == end) {  
  32.             return null  
  33.         }  
  34.   
  35.         val filtered = SpannableStringBuilder(source, start, end)  
  36.         val start2 = i - start  
  37.         val end2 = end - start  
  38.   
  39.         for (j in end2 - 1 downTo start2) {  
  40.             if (source[j] == '\n') {  
  41.                 filtered.delete(j, j + 1)  
  42.             }  
  43.         }  
  44.   
  45.         return filtered  
  46.     }  
  47. }  

0 件のコメント:

コメントを投稿