我有三个编辑文本字段。在这些字段中,我想仅为第一个字段显示软输入键盘,为后两个字段禁用这些字段,这些是日期和时间字段。
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);
}
如果软键盘已经打开,我怎么能隐藏它?
答案 0 :(得分:11)
// 活动
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);
}
}
答案 1 :(得分:0)
简单的方法是使用xml
users: [
{
"name": "name1",
"phone": "111111111",
"address": "address1",
"city": "city1",
"pcap": 1111,
"note": ""
},
{
"name": "name2",
"phone": "222222222",
"address": "address2",
"city": "city2",
"pcap": 2222,
"note": ""
},
{
"name": "name3",
"phone": "333333333",
"address": "address3",
"city": "city3",
"pcap": 3333,
"note": ""
},
{
"name": "name4",
"phone": "44444444",
"address": "address4",
"city": "city4",
"pcap": 4444,
"note": ""
}
]
答案 2 :(得分:0)
您可以将两个属性设置为edittext
android:focusable="false"
android:focusableInTouchMode="false"
注意:这样您的edittext可以点击日期和时间不会聚焦到软键盘
答案 3 :(得分:0)
检查当前焦点是否不为null,否则可能导致null指针异常
if (getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}