2016-07-16 46 views
2

我有三個編輯文本字段。在這些字段中,我希望僅爲第一個字段顯示軟輸入鍵盤,並在後兩個字段中顯示禁用的日期和時間字段。隱藏Android軟鍵盤(如果打開的話)

Edit-Text 1 //Show the keyboard 
Edit-Text 2 and 3 //Hide the keyboard 

通過使用下面的代碼,我能夠禁用鍵盤場2和3,但是當用戶集中於1場的鍵盤出現,但是當用戶點擊場2或3並沒有隱瞞。儘管先敲擊第2或第3場,但不會出現鍵盤。

//Code to disable soft input keyboard 
public static void disableSoftInputFromAppearing(EditText editText) { 
    if (Build.VERSION.SDK_INT >= 11) { 
     editText.setRawInputType(InputType.TYPE_CLASS_TEXT); 
     editText.setTextIsSelectable(true); 
    } else { 
     editText.setRawInputType(InputType.TYPE_NULL); 
     editText.setFocusable(true); 
    } 

如何隱藏軟輸入鍵盤,如果它已經打開?

回答

8

// 活動

public static void hideSoftKeyboard(Activity activity) { 

    InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE); 
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 
} 

// 片段

public void hideSoftKeyboard() { 
    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); 
    inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); 
} 

// 如果編輯文本地失去焦點隱藏鍵盤

edTxtMessage.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (isEditable){ 
       v.setFocusable(true); 
       v.setFocusableInTouchMode(true); 
      } else { 
       edTxtMessage.setFocusable(false); 
      } 

      return false; 
     } 
    }); 

edTxtMessage.setOnFocusChangeListener(new View.OnFocusChangeListener({ 
     @Override 
     public void onFocusChange(View view, boolean b) { 
      if (!b){ 
       hideKeyboard(getContext(), view); 
      } 
     } 
    }); 

private void hideKeyboard(Context context, View view) { 
    if (view != null) { 
     InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
     imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
    } 
} 
+0

我在片段上 – Paras

0

容易的方法是使用XML

android:inputType="none" 
android:textIsSelectable="true 
+0

我已經試過了。如果我點擊第一個字段,鍵盤就會出現,直到我按下向下按鈕纔會消失 – Paras

0

您可以設置兩個屬性到您的EditText

android:focusable="false" 
    android:focusableInTouchMode="false" 

注:這是你的EditText是可點擊的日期和時間不專注於軟鍵盤

+0

實際上,我在點對點事件時觸發了日期時間選擇器,因爲在點擊時它被稱爲第二次聚焦後。 – Paras

+0

我沒有得到? –