3

我的屏幕上有一个切换按钮。如果我单击此按钮,我需要一个键盘才能显示在屏幕上。这是我现在拥有的代码,但它没有按预期显示键盘:(

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);          }
        }
    };

当我单击键盘切换按钮时,我在 LogCat 中看到它进入 if/else 块,但否则不会在屏幕上显示任何键盘。有人可以帮忙吗?

4

2 回答 2

3

随着showSoftInput你试图聚焦你的keyboard按钮并开始向它发送键盘事件,但它是不可聚焦的。让它像这样聚焦(在你的onCreate):

keyboard.setFocusable(true);
keyboard.setFocusableInTouchMode(true);
于 2013-04-10T14:28:42.617 回答
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);
     }
于 2014-12-02T05:13:42.793 回答