Giới thiệu
Ví dụ này minh họa cách giới hạn EditText chỉ cho phép nhập chữ cái (A-Z, a-z) và khoảng trắng, chặn số và ký tự đặc biệt bằng InputFilter trong Android Kotlin.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project, điền thông tin.
Bước 2: Giao diện (res/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="2dp"
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" />
</RelativeLayout>
Bước 3: MainActivity.kt
import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.widget.EditText
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 chỉ cho phép chữ cái và khoảng trắng
val alphaFilter = InputFilter { source, start, end, dest, dstart, dend ->
val input = source.subSequence(start, end).toString()
if (input.matches(Regex("^[a-zA-Z\\s]*$"))) {
null // chấp nhận
} else {
"" // chặn
}
}
editText.filters = arrayOf(alphaFilter)
}
}
Bước 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<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>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Thử nhập số hoặc ký tự đặc biệt vào EditText → sẽ không được nhập.
Mở rộng: Dùng android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " trong XML cho trường hợp đơn giản, nhưng InputFilter linh hoạt hơn (hỗ trợ regex, logic phức tạp).