ภาพรวม
ตัวอย่างนี้สาธิตวิธีใช้เมธอด replaceAll() เพื่อแทนที่ช่องว่างทั้งหมดในข้อความจาก EditText ด้วยสตริงว่าง แล้วแสดงผลใน TextView
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
ในโค้ดข้างต้น เรามี EditText สำหรับรับชื่อ เมื่อผู้ใช้กดปุ่ม โปรแกรมจะนำข้อมูลไปแทนที่ช่องว่างทั้งหมด
ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = name.getText().toString();
if (!input.isEmpty()) {
// แทนที่ช่องว่างทั้งหมดด้วยสตริงว่าง
String replaced = input.replaceAll("\\s", "");
text.setText(replaced);
} else {
name.setError("Plz enter name");
}
}
});
}
}
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ

ในผลลัพธ์ ให้ป้อนสตริงว่า "Krishna sai sai" โปรแกรมจะแทนที่ช่องว่างทั้งหมดด้วยค่าว่าง ได้ผลลัพธ์ "Krishnasaisai"