以编程方式显示软键盘-不工作



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

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块,但在屏幕上不显示任何键盘。有人能帮帮我吗?

使用showSoftInput,您试图聚焦keyboard按钮并开始向其发送键盘事件,但它无法聚焦。让它像这样对焦(在你的onCreate):

keyboard.setFocusable(true);
keyboard.setFocusableInTouchMode(true);

你可以试试这个(在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);
     }

相关内容

  • 没有找到相关文章

最新更新