ภาพรวม
ตัวอย่างนี้สาธิตวิธีตรวจสอบว่าข้อความใน TextView ประกอบด้วยตัวเลขเท่านั้น (Digits Only) ใน Android โดยใช้ TextUtils.isDigitsOnly()
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// ตั้งค่าข้อความทดสอบ
textView.setText("123456789");
// ตรวจสอบว่าเป็นตัวเลขทั้งหมดหรือไม่
boolean isDigitsOnly = TextUtils.isDigitsOnly(textView.getText());
Toast.makeText(MainActivity.this, "Is digits only: " + isDigitsOnly, Toast.LENGTH_LONG).show();
}
}
การทดสอบ
รันแอป จะแสดง Toast "Is digits only: true" ลองเปลี่ยนข้อความใน TextView เป็น "123abc" จะได้ false
วิธีการตรวจสอบตัวเลขอื่นๆ
1. ใช้ Regular Expression
String text = textView.getText().toString();
boolean isNumeric = text.matches("\\d+"); // true ถ้ามีเฉพาะ 0-9
2. ใช้ Apache Commons Lang (ถ้ามีในโปรเจกต์)
boolean isNumeric = org.apache.commons.lang3.StringUtils.isNumeric(text);
3. ตรวจสอบ EditText แบบ Real-time (TextWatcher)
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean onlyDigits = TextUtils.isDigitsOnly(s);
// ทำงานตามผลลัพธ์ เช่น เปิด/ปิดปุ่ม Submit
submitButton.setEnabled(onlyDigits);
}
@Override
public void afterTextChanged(Editable s) {}
});
4. กำหนด InputType ให้ EditText (ป้องกันการกรอกตัวอักษร)
<EditText
android:inputType="number"
android:digits="0123456789" />
ความแตกต่างของเมธอด
| เมธอด | คืนค่า true สำหรับ | หมายเหตุ |
|---|---|---|
| TextUtils.isDigitsOnly() | 0-9 เท่านั้น | มาตรฐาน Android ไม่ต้อง import เพิ่ม |
| String.matches("\\d+") | 0-9 เท่านั้น | ใช้ Regex ยืดหยุ่นกว่า |
| StringUtils.isNumeric() | 0-9 และตัวเลข Unicode | ต้องเพิ่ม library |