บทนำ
ตัวอย่างนี้แสดงวิธีใช้ InputFilter.LengthFilter เพื่อจำกัดจำนวนตัวอักษรสูงสุดที่พิมพ์ได้ใน EditText
ขั้นตอนที่ 1: สร้างโปรเจกต์
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_marginHorizontal="24dp"
android:hint="Max 15 characters"
android:inputType="text"
android:padding="16dp"
android:textSize="18sp" />
</RelativeLayout>
ขั้นตอนที่ 3: MainActivity.kt
import android.os.Bundle
import android.text.InputFilter
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "InputFilter Demo"
editText = findViewById(R.id.editText)
val maxTextLength = 15
editText.filters = arrayOf(InputFilter.LengthFilter(maxTextLength))
Toast.makeText(this, "EditText limit set to $maxTextLength characters", Toast.LENGTH_SHORT).show()
}
}
ขั้นตอนที่ 4: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.inputfilter">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
InputFilter ประเภทอื่นๆ ที่มีประโยชน์
1. InputFilter.AllCaps - ตัวพิมพ์ใหญ่ทั้งหมด
editText.filters = arrayOf(InputFilter.AllCaps())
2. Custom InputFilter - อนุญาตเฉพาะตัวเลขและจุดทศนิยม
class DecimalDigitsInputFilter(private val digitsBeforeDecimal: Int, private val digitsAfterDecimal: Int) : InputFilter {
override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
val result = StringBuilder(dest).delete(dstart, dend).insert(dstart, source.subSequence(start, end)).toString()
return if (result.matches(Regex("^\\d{0,$digitsBeforeDecimal}(\\.\\d{0,$digitsAfterDecimal})?\$"))) {
null // ยอมรับ
} else {
"" // ปฏิเสธ
}
}
}
// ใช้งาน: สูงสุด 5 ตัวเลขก่อนจุด 2 ตัวหลังจุด
editText.filters = arrayOf(DecimalDigitsInputFilter(5, 2))
3. Custom InputFilter - ห้ามอักขระพิเศษ
class NoSpecialCharsFilter : InputFilter {
private val blockedRegex = Regex("[^a-zA-Z0-9\\s]")
override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
val input = source?.subSequence(start, end).toString() ?: return ""
return if (blockedRegex.containsMatchIn(input)) "" else null
}
}
editText.filters = arrayOf(NoSpecialCharsFilter())
4. รวมหลาย Filter พร้อมกัน
editText.filters = arrayOf(
InputFilter.LengthFilter(20),
InputFilter.AllCaps(),
NoSpecialCharsFilter()
)
XML Attribute ทางเลือก (API 21+)
สามารถกำหนดใน XML ได้เลย:
<EditText
android:id="@+id/editText"
android:maxLength="15"
android:inputType="textCapCharacters"
... />
การจัดการ Paste (วางข้อความ)
InputFilter ทำงานกับการพิมพ์และการ Paste ทั้งคู่ หาก Paste ข้อความยาวเกิน Limit จะถูกตัดให้เหลือตามที่กำหนด
TextWatcher สำหรับการนับตัวอักษร Real-time
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
val remaining = maxTextLength - s?.length ?: 0
charCountTextView.text = "$remaining/$maxTextLength"
}
})