我的屏幕上有一个togglebutton。如果我点击此按钮,我需要一个键盘显示在屏幕上。这是我现在的代码,但它没有按预期显示键盘:(
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
keyboard = (ToggleButton) findViewById(R.id.keyboard);
keyboard.setOnClickListener(displayKeyboard);
}
OnClickListener displayKeyboard = new OnClickListener(){
@Override
public void onClick(View v) {
if(client == null)
return;
boolean on = ((ToggleButton) v).isChecked();
if(on){ // show keyboard
System.out.println("Togglebutton is ON");
keyboard.requestFocus();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(keyboard, InputMethodManager.SHOW_IMPLICIT);
}
else{ // hide keyboard
System.out.println("Togglebutton is OFF");
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(keyboard.getWindowToken(), 0); }
}
};
当我点击键盘togglebutton时,我在LogCat中看到它进入了if / else块,但是否则在屏幕上没有显示任何键盘。有人可以帮忙吗?
答案 0 :(得分:3)
使用showSoftInput
,您试图关注keyboard
按钮并开始向其发送键盘事件,但它无法调焦。像这样(在你的onCreate
中)使其可聚焦:
keyboard.setFocusable(true);
keyboard.setFocusableInTouchMode(true);
答案 1 :(得分:1)
你可以尝试这个(在UTILITY类中):
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public static void showSoftKeyboard(Activity activity, View focusedView)
{
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}