Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้าง EditText ที่รับเฉพาะตัวอักษรภาษาอังกฤษใน Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีจำกัดการป้อนข้อมูลใน EditText ให้รับเฉพาะตัวอักษรภาษาอังกฤษ (A-Z, a-z) โดยใช้ InputFilter

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project

ขั้นตอนที่ 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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:hint="Enter alphabets only"
        android:inputType="textCapWords" />

</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.kt

import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val editText = findViewById<EditText>(R.id.editText)

        // Filter: รับเฉพาะ A-Z, a-z และ Space
        val alphaFilter = InputFilter { source, start, end, dest, dstart, dend ->
            val input = source.subSequence(start, end).toString()
            if (input.matches("^[a-zA-Z ]*$".toRegex())) {
                null // ยอมรับ
            } else {
                // แจ้งเตือนและปฏิเสธ
                runOnUiThread { 
                    Toast.makeText(this@MainActivity, "Only alphabets allowed", Toast.LENGTH_SHORT).show() 
                }
                "" // ปฏิเสธอักขระที่ไม่ผ่าน
            }
        }

        editText.filters = arrayOf(alphaFilter)
    }
}

วิธีอื่นๆ

1. ใช้ android:digits ใน XML (ง่ายที่สุด)

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
    android:hint="Enter alphabets only" />

2. ใช้ KeyListener (ควบคุมระดับแป้นพิมพ์)

import android.text.method.DigitsKeyListener

editText.keyListener = DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")

3. รองรับภาษาไทย (Thai Characters)

// รับเฉพาะตัวอักษรไทยและอังกฤษ
val thaiAlphaFilter = InputFilter { source, start, end, dest, dstart, dend ->
    val input = source.subSequence(start, end).toString()
    if (input.matches("^[a-zA-Zก-ฮะ-์ ]*$".toRegex())) {
        null
    } else {
        ""
    }
}

ขั้นตอนที่ 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.alphabetonly">
    <application ... >
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

การทดสอบ

รันแอป พยายามพิมพ์ตัวเลข หรือสัญลักษณ์ จะไม่สามารถพิมพ์ได้ และแสดง Toast แจ้งเตือน

หมายเหตุ

  • android:digits วิธีง่ายที่สุด แต่ไม่สามารถปรับแต่งข้อความแจ้งเตือนได้
  • InputFilter ยืดหยุ่นที่สุด สามารถเพิ่ม Logic ซับซ้อนได้
  • ควรทดสอบกับ Keyboard ต่างๆ (Gboard, Samsung Keyboard, ฯลฯ) เพราะบางตัวอาจส่ง Input แบบต่างกัน
  • สำหรับ Password field ควรใช้ android:inputType="textVisiblePassword" ร่วมกับ Filter