使用場景:EditText輸入完畢後,點選螢幕其他區域,關閉輸入法。
思路:
1、讓EditText失去焦點,即讓EditText所在的布局layout擷取焦點;
2、隐藏輸入法。
例一:使LinearLayout布局下的EditText,在輸入完畢後,點選螢幕其他區域,關閉輸入法:
LinearLayout linearLayout =(LinearLayout)findViewById(R.Id.linearLayout );
linearLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//-------------------------------------------------
//讓linearLayout擷取焦點
linearLayout.setFocusable(true);
linearLayout.setFocusableInTouchMode(true);
linearLayout.requestFocus();
//-------------------------------------------------
//隐藏輸入法
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(linearLayout.getWindowToken(), );
return false;
}
});
拓展:當應用包含較多EditText時,将該方法寫到一個類中,用時調用更為便捷:
public class LostFocus {
/***************************************************************************
*
* 使線性布局中的EditText失去焦點,并隐藏輸入法。
*
***************************************************************************/
public void linearLayout(final LinearLayout linearLayout,final Context context) {
linearLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//-------------------------------------------------
//linearLayout擷取焦點
linearLayout.setFocusable(true);
linearLayout.setFocusableInTouchMode(true);
linearLayout.requestFocus();
//-------------------------------------------------
//隐藏輸入法
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(linearLayout.getWindowToken(), );
return false;
}
});
}
/***************************************************************************
*
* 使相對布局中的EditText失去焦點,并隐藏輸入法。
*
***************************************************************************/
public void relativeLayout(final RelativeLayout relativeLayout,final Context context) {
relativeLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//-------------------------------------------------
//relativeLayout擷取焦點
relativeLayout.setFocusable(true);
relativeLayout.setFocusableInTouchMode(true);
relativeLayout.requestFocus();
//-------------------------------------------------
//隐藏輸入法
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(relativeLayout.getWindowToken(), );
return false;
}
});
}
}
在MainActivity中使RelativeLayout布局下的EditText,在輸入完畢後,點選螢幕其他區域,關閉輸入法:
// --------------------------------------------------------------------------------
LostFocus mLostFocus = new LostFocus();
RelativeLayout mRelativeLayout = (RelativeLayout)
findViewById(R.id.relative_layout_login);
// --------------------------------------------------------------------------------
mLostFocus.relativeLayout(mRelativeLayout, MainActivity.this);