Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Hiển thị bàn phím mềm khi EditText focus trong Android

Hiển thị bàn phím mềm khi EditText focus trong Android

Hướng dẫn này minh họa cách tự động hiển thị bàn phím ảo (soft keyboard) khi EditText nhận focus.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (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_centerInParent="true"
        android:hint="Nhập văn bản..."/>
</RelativeLayout>

Bước 3: Code 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;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        editText = findViewById(R.id.editText);
        showSoftKeyboard(editText);
    }
    
    public void showSoftKeyboard(View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager) 
                getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }
}

Bước 4: Cấu hình 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>

Chạy ứng dụng

Kết nối thiết bị, chạy app. EditText sẽ tự động nhận focus và bàn phím ảo hiện ra ngay lập tức.

Các cách khác để hiển thị/ẩn bàn phím:
// 1. Trong onCreate - sử dụng Window flag (khuyến khích cho activity chính)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

// 2. Trong Manifest - cho activity
<activity android:name=".MainActivity"
    android:windowSoftInputMode="stateVisible">

// 3. Hiển thị bàn phím cho EditText cụ thể
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

// 4. Ẩn bàn phím
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
// Hoặc
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

// 5. Toggle (bật/tắt)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

Các flag SOFT_INPUT_MODE hữu ích

FlagMô tả
stateVisibleLuôn hiển thị bàn phím khi activity hiện
stateHiddenLuôn ẩn bàn phím
stateUnchangedGiữ trạng thái hiện tại
stateAlwaysHiddenẨn bàn phím, ngay cả khi user tap vào EditText
adjustResizeResize layout để làm chỗ cho bàn phím (mặc định)
adjustPanPan (cuộn) layout để EditText focus hiển thị
adjustNothingKhông điều chỉnh layout

Kết hợp: android:windowSoftInputMode="stateVisible|adjustResize"

Best Practices

  • Dùng android:windowSoftInputMode trong Manifest cho trường hợp phổ biến
  • Dùng code Java/Kotlin khi cần logic phức tạp (ví dụ: hiển thị sau khi load data xong)
  • Luôn kiểm tra view.requestFocus() trả về true trước khi show keyboard
  • Đừng quên ẩn bàn phím khi không cần thiết (ví dụ: nhấn back, chuyển màn hình)