2014-01-07 157 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的意见,如果用户点击其他地方,它会隐藏键盘。如果您有任何复杂的自定义布局,则可以排除其他视图,如果用户单击该视图,则不会隐藏键盘。

它为我工作。希望它可以帮助你。

相关问题