Android問題集(四)——EditText輸入完畢後,擊螢幕其它區域,隱藏/關閉輸入法
阿新 • • 發佈:2019-02-19
使用場景: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(), 0);
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(), 0);
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(), 0);
return false;
}
});
}
}
在MainActivity中使RelativeLayout佈局下的EditText,在輸入完畢後,點選螢幕其他區域,關閉輸入法:
// --------------------------------------------------------------------------------
LostFocus mLostFocus = new LostFocus();
RelativeLayout mRelativeLayout = (RelativeLayout)
findViewById(R.id.relative_layout_login);
// --------------------------------------------------------------------------------
mLostFocus.relativeLayout(mRelativeLayout, MainActivity.this);