ภาพรวม
ตัวอย่างนี้สาธิตวิธีการจำกัดจำนวนตัวอักษรสูงสุดที่พิมพ์ได้ใน EditText โดยใช้ InputFilter.LengthFilter
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดทำ Layout (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"
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" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
int maxTextLength = 15;
// ตั้งค่า InputFilter จำกัดความยาว
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxTextLength)});
Toast.makeText(this, "จำกัด EditText ไว้ 15 ตัวอักษร", Toast.LENGTH_SHORT).show();
}
}
ขั้นตอนที่ 4: กำหนดค่า AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<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 อื่นๆ ที่น่าสนใจ
| Filter | การใช้งาน |
|---|---|
InputFilter.LengthFilter(int max) |
จำกัดจำนวนตัวอักษรสูงสุด |
InputFilter.AllCaps() |
บังคับให้เป็นตัวพิมพ์ใหญ่ทั้งหมด |
new InputFilter() { ... } |
สร้าง Filter กำหนดเอง (เช่น อนุญาตเฉพาะตัวเลข) |
ตัวอย่าง Filter กำหนดเอง (เฉพาะตัวเลข)
InputFilter numericFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isDigit(source.charAt(i))) {
return ""; // ปฏิเสธตัวอักษรที่ไม่ใช่ตัวเลข
}
}
return null; // ยอมรับ
}
};
editText.setFilters(new InputFilter[]{numericFilter, new InputFilter.LengthFilter(10)});
การทดสอบ
รันแอปบนอุปกรณ์จริง พิมพ์ใน EditText จะพิมพ์ได้สูงสุด 15 ตัวอักษรเท่านั้น

