2013-07-05 128 views
4

我正在用edittext和一個按鈕製作應用程序。當我在edittext中輸入內容然後點擊一個按鈕時,我需要鍵盤並專注於edittext消失,但我似乎無法做到。按下按鈕時清除edittext焦點並隱藏鍵盤

我插入這2行代碼在XML:

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

我也試圖在按鈕點擊方法補充一點:

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

它只是將無法正常工作後,我按下按鈕,鍵盤保持在那裏,edittext仍然有焦點。

回答

10

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

<!-- 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(); 
+1

對我不起作用 –

6

隱藏鍵盤調用此:

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

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

+2

這是正確的答案 –

0
InputMethodManager inputManager = (InputMethodManager) 
            getSystemService(Context.INPUT_METHOD_SERVICE); 

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

添加以下你的按鈕onclick事件

您需要import android.view.inputmethod.InputMethodManager ;

當您單擊按鈕時,鍵盤將隱藏並清除文本。

相關問題