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

วิธีซ่อนแป้นพิมพ์นิ่มเมื่อคลิกนอก EditText ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีปิด Soft Keyboard อัตโนมัติเมื่อผู้ใช้กดที่พื้นที่ว่าง (นอก EditText) ซึ่งเป็น UX ที่ดี เพราะ Keyboard จะไม่ค้างอยู่บนหน้าจอ

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="16dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:hint="Enter text here"
        android:textSize="20sp" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:onClick="setText"
        android:text="Set Text"
        android:textStyle="bold"/>

</LinearLayout>

💡 จุดสำคัญใน XML

Root Layout ต้องมี android:focusable="true" และ android:focusableInTouchMode="true" เพื่อให้รับ Focus ได้เมื่อคลิกพื้นที่ว่าง

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

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
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);
    }

    // เรียกจากปุ่ม "Set Text" (android:onClick="setText")
    public void setText(View view) {
        String newText = editText.getText().toString();
        textView.setText(newText);
        closeKeyboard();
    }

    // เมธอดปิด Keyboard
    private void closeKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) 
                getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

ขั้นตอนที่ 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 จะขึ้น Keyboard → กดที่พื้นที่ว่าง (TextView หรือพื้นที่ว่าง) → Keyboard จะหาย

วิธีซ่อนแป้นพิมพ์นิ่มเมื่อคลิกนอก EditText ใน Android วิธีซ่อนแป้นพิมพ์นิ่มเมื่อคลิกนอก EditText ใน Android

วิธีอื่น: ใช้ OnTouchListener บน Root View

// ใน onCreate
findViewById(R.id.rootLayout).setOnTouchListener((v, event) -> {
    closeKeyboard();
    return false; // ส่งต่อ Event ให้ View อื่นด้วย
});

สำหรับ Fragment

// ใน Fragment
private void closeKeyboard() {
    View view = getActivity().getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) 
            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

สำหรับ Kotlin (Extension Function)

// Extension function
fun Activity.hideKeyboard() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    currentFocus?.let { imm.hideSoftInputFromWindow(it.windowToken, 0) }
}

// ใช้งาน
binding.root.setOnTouchListener { _, _ -> 
    hideKeyboard() 
    false
}