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

วิธีนับจำนวนตัวอักษรใน EditText ขณะพิมพ์ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการนับจำนวนตัวอักษรใน EditText แบบ Real-time โดยใช้ TextWatcher แสดงผลใน TextView เหมาะสำหรับจำกัดความยาวข้อความ (เช่น SMS, Tweet, Bio)

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="Character Count: 0"
        android:textSize="24sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Type here..."
        android:inputType="textMultiLine"
        android:maxLength="200"
        android:gravity="top" />

</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private TextView textView;

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

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        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) {
                // เรียกขณะเปลี่ยนแปลง - s คือข้อความปัจจุบัน (หลังเปลี่ยนแล้ว)
                int length = s.length();
                updateCounter(length);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // เรียกหลังเปลี่ยนแปลงเสร็จ - เหมาะสำหรับ format ข้อความ
            }
        });
    }

    private void updateCounter(int count) {
        textView.setText("Character Count: " + count);
        
        // เปลี่ยนสีตามจำนวนตัวอักษร (ตัวอย่าง)
        if (count > 180) {
            textView.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        } else if (count > 150) {
            textView.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
        } else {
            textView.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        }
    }
}

💡 จุดสำคัญ: ใช้ onTextChanged แทน beforeTextChanged

โค้ดต้นฉบับใช้ beforeTextChanged ซึ่ง s ยังเป็นข้อความเก่า ทำให้นับผิด ควรใช้ onTextChanged เพราะ s เป็นข้อความใหม่แล้ว

ขั้นตอนที่ 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>
                
                
            </intent-filter>
        </activity>

    </application>
</manifest>

การทดสอบ

รันแอป → พิมพ์ข้อความใน EditText → ตัวนับจะอัปเดตทันที → เปลี่ยนสีเมื่อเกินเกณฑ์

วิธีนับจำนวนตัวอักษรใน EditText ขณะพิมพ์ใน Android วิธีนับจำนวนตัวอักษรใน EditText ขณะพิมพ์ใน Android

การปรับปรุง: แสดง "ตัวอักษรที่เหลือ" แทน

private static final int MAX_LENGTH = 200;

private void updateCounter(int currentLength) {
    int remaining = MAX_LENGTH - currentLength;
    textView.setText("Remaining: " + remaining + " / " + MAX_LENGTH);
    
    if (remaining < 0) {
        textView.setTextColor(Color.RED);
    } else if (remaining < 20) {
        textView.setTextColor(Color.parseColor("#FF9800")); // Orange
    } else {
        textView.setTextColor(Color.parseColor("#4CAF50")); // Green
    }
}

ใช้ android:maxLength ใน XML

สามารถจำกัดความยาวได้โดยตรงใน XML (ไม่ต้องเขียนโค้ด):

<EditText
    ...
    android:maxLength="200" />

แต่จะไม่แสดงตัวนับ Real-time ต้องใช้ TextWatcher ร่วมกับ

สำหรับ Kotlin (Extension Function)

// Extension สำหรับนับตัวอักษร
fun EditText.setupCharacterCounter(counterTextView: TextView, maxLength: Int) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            val current = s?.length ?: 0
            val remaining = maxLength - current
            counterTextView.text = "$remaining / $maxLength"
            counterTextView.setTextColor(when {
                remaining < 0 -> Color.RED
                remaining < 20 -> Color.parseColor("#FF9800")
                else -> Color.parseColor("#4CAF50")
            })
        }
        
        override fun afterTextChanged(s: Editable?) {}
    })
}

// ใช้งาน
editText.setupCharacterCounter(textView, 200)