我有三个编辑文本字段.在这些字段中,我想仅为第一个字段显示软输入键盘,而在后两个字段中禁用这些字段,这些是日期和时间字段.
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);
}
如果软键盘已经打开,如何隐藏它?
解决方法:
//活动
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);
}
}