一、通過布局文件實現自動隱藏軟鍵盤
在布局文件的根標籤中加入以下屬性:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:focusableInTouchMode="true">
其中,android:focusableInTouchMode="true"
是用來在布局文件載入時自動隱藏軟鍵盤,讓用戶能夠通過點擊屏幕其他區域來隱藏軟鍵盤。
如果想通過按鈕點擊等方式來控制軟鍵盤顯示和隱藏,可以在對應的View中添加onClick()
方法,利用InputMethodManager
來控制軟鍵盤的顯示和隱藏。
EditText editText = findViewById(R.id.editText); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
二、通過代碼實現動態隱藏軟鍵盤
在代碼中調用InputMethodManager
的hideSoftInputFromWindow()
方法來隱藏軟鍵盤。
EditText editText = findViewById(R.id.editText); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
其中,需要傳入當前EditText的WindowToken參數,以表明需要隱藏的軟鍵盤是哪一個。
三、通過自定義控制項實現更加靈活的軟鍵盤控制
自定義控制項可以讓開發人員根據實際需求來實現更加靈活的軟鍵盤控制,比如點擊EditText時自動彈出軟鍵盤,點擊其他區域或按下返回鍵時自動隱藏軟鍵盤等等。
需要在自定義控制項的代碼中實現OnTouchListener
和OnFocusChangeListener
等介面,以實現軟鍵盤的顯示和隱藏。
public class CustomEditText extends EditText implements View.OnTouchListener, View.OnFocusChangeListener { private Context context; public CustomEditText(Context context) { super(context); init(context); } public CustomEditText(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { this.context = context; setOnTouchListener(this); setOnFocusChangeListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { showSoftKeyboard(); return true; } @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideSoftKeyboard(); } } private void showSoftKeyboard() { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT); } private void hideSoftKeyboard() { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }
需要注意的是,在使用自定義控制項的時候需要在布局文件中引入該控制項,而不是普通的EditText。
<com.example.myapplication.CustomEditText android:id="@+id/customEditText" android:layout_width="match_parent" android:layout_height="wrap_content"/>
四、總結
本文介紹了三種實現Android軟鍵盤隱藏的方式,其中第一種是在布局文件中添加屬性來自動隱藏軟鍵盤,第二種是通過代碼動態控制軟鍵盤的顯示和隱藏,第三種是通過自定義控制項實現更加靈活的軟鍵盤控制。
開發人員可以根據實際需求來選擇不同的實現方式,以便更好地滿足用戶的交互體驗。
原創文章,作者:FKZW,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/132122.html