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

วิธีตรวจสอบ EditText ว่างเปล่าใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีตรวจสอบว่า EditText ว่างหรือไม่ โดยใช้ TextUtils.isEmpty() ซึ่งเป็น Best Practice

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

เปิด Android Studio → File → New Project และกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: เลย์เอาต์ (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:textSize="16sp"
        android:layout_marginTop="45dp"
        android:hint="Enter text here"
        android:padding="16dp" />

    <Button
        android:id="@+id/buttonCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check EditText"
        android:layout_centerInParent="true"
        android:layout_below="@id/editText"
        android:layout_marginTop="25dp" />

</RelativeLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        button = findViewById(R.id.buttonCheck);

        button.setOnClickListener(v -> {
            String input = editText.getText().toString();
            
            // ใช้ TextUtils.isEmpty() - ตรวจสอบ null และ empty string
            if (TextUtils.isEmpty(input)) {
                Toast.makeText(MainActivity.this, 
                    "Empty field not allowed!", 
                    Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, 
                    "Proceed.. Input: " + input, 
                    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>

การทดสอบ

รันแอป เว้นว่างกด Check -> แสดง "Empty field not allowed!" กรอกข้อความกด Check -> แสดง "Proceed.."

วิธีตรวจสอบ EditText ว่างเปล่าใน Android วิธีตรวจสอบ EditText ว่างเปล่าใน Android

วิธีตรวจสอบ EditText ว่าง - เปรียบเทียบ

วิธีCodeตรวจสอบ Nullตรวจสอบ Emptyตรวจสอบ Whitespaceแนะนำ
TextUtils.isEmpty()TextUtils.isEmpty(str)✓✓✗✅ Best Practice
TextUtils.isEmpty(trim)TextUtils.isEmpty(str.trim())✓✓✓✅ สำหรับ Trim
str == null || str.isEmpty()str == null || str.isEmpty()✓✓✗Manual
str.trim().isEmpty()str != null && str.trim().isEmpty()✓✓✓Manual + Trim
EditText.getText().length()editText.getText().length() == 0✗ (Crash ถ้า null)✓✗❌ ไม่แนะนำ

Best Practice: Helper Method

public static boolean isEmpty(EditText editText) {
    return TextUtils.isEmpty(editText.getText().toString().trim());
}

public static boolean isEmpty(CharSequence charSequence) {
    return TextUtils.isEmpty(charSequence?.toString()?.trim());
}

// ใช้งาน
if (isEmpty(editText)) {
    editText.setError("Field required");
    return;
}

การตั้งค่า Error บน EditText เอง (UX ดีกว่า)

button.setOnClickListener(v -> {
    String input = editText.getText().toString().trim();
    
    if (TextUtils.isEmpty(input)) {
        editText.setError("This field is required");
        editText.requestFocus();
        return;
    }
    
    // Clear error
    editText.setError(null);
    
    // Proceed...
});

Input Validation เพิ่มเติม

// Email
if (!Patterns.EMAIL_ADDRESS.matcher(input).matches()) {
    editText.setError("Invalid email format");
}

// Phone
if (!Patterns.PHONE.matcher(input).matches()) {
    editText.setError("Invalid phone number");
}

// Password length
if (input.length() < 8) {
    editText.setError("Password must be at least 8 characters");
}