簡體   English   中英

按下按鈕時清除編輯文本焦點並隱藏鍵盤

[英]Clear edittext focus and hide keyboard when button is pressed

我正在制作一個帶有編輯文本和按鈕的應用程序。 當我在edittext 中輸入一些內容然后單擊一個按鈕時,我希望鍵盤和edittext 上的焦點消失,但我似乎無法做到。

我在 XML 中插入了這兩行代碼:

android:focusable="true"
android:focusableInTouchMode="true"

我還嘗試在按鈕單擊方法中添加它:

edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

它只是不起作用,在我按下按鈕后,鍵盤保持在那里並且 edittext 仍然具有焦點。

要隱藏鍵盤,請調用:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);

您還可以查看此解決方案: https : //stackoverflow.com/a/15587937/786337

另一個解決方案是,創建一個虛擬布局

<!-- Dummy item for focus at startup -->
<LinearLayout
    android:id="@+id/dummy_id"
    android:orientation="vertical"
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />

並在您的onButtonClickFunction設置焦點

((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();
InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);
editText.setText("");

在您的按鈕 onclick 事件中添加以下內容

您需要import android.view.inputmethod.InputMethodManager

單擊按鈕時,鍵盤會隱藏和清除文本。

首先,您必須禁用鍵盤:

void hideKeyboard(Activity activity) { View view = activity.getCurrentFocus(); InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); assert manager != null && view != null; manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }

第二個清晰的視圖(布局、編輯文本...)焦點:

view.clearFocus

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM