2014-01-07 68 views
3

我有一個EditText,我想控制鍵盤。當EditText有焦點時,鍵盤應該出現,然後一旦我點擊其他視圖,我想讓鍵盤消失。我嘗試下面的代碼,但它的工作EditText失去焦點時關閉鍵盤

mEditText.setOnFocusChangeListener(new OnFocusChangeListener() { 

      @Override 
      public void onFocusChange(View v, boolean hasFocus) { 
       if (hasFocus) { 
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 
       } else { 
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 
       } 

      } 
     }); 
+0

你還有問題嗎?讓我知道如果你仍然需要幫助。 –

回答

1

假設你的最外層佈局RelativeLayout(你可以爲別人以及類似的東西),你可以這樣做以下:

private RelativeLayout layout; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //.... 
    layout = (RelativeLayout) findViewById(R.id.yourOutermostLayout); 
    onTapOutsideBehaviour(layout); 
} 

private void onTapOutsideBehaviour(View view) { 
    if(!(view instanceof EditText) || !(view instanceof Button)) { 
     view.setOnTouchListener(new OnTouchListener() { 
      public boolean onTouch(View v, MotionEvent event) { 
       hideSoftKeyboard(YourCurrentActivity.this); 
       return false; 
      } 

     }); 
    } 
} 


\\Function to hide keyboard 
private static void hideSoftKeyboard(Activity activity) { 
    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); 
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 
} 

onTapOutsideBehaviour功能在這裏,其他的是你的EditTextButton的意見,如果用戶點擊其他地方,它會隱藏鍵盤。如果您有任何複雜的自定義佈局,則可以排除其他視圖,如果用戶單擊該視圖,則不會隱藏鍵盤。

它爲我工作。希望它可以幫助你。

相關問題