Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Soft Keyboard Programmatically - not working

I have a togglebutton in my screen. If I click on this button, I need a keyboard to show up on the screen. This is the code I have right now, but it doesnt display the keyboard as expected :(

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

When I click the keyboard togglebutton, I see in LogCat that it goes into the if/else block, but otherwise doesnt display any keyboard on screen. can someone please help?

like image 746
crypto9294 Avatar asked May 10 '26 14:05

crypto9294


2 Answers

With the showSoftInput you are trying to focus your keyboard button and to start sending keyboard events to it, but it is not focusable. Make it focusable like this (in your onCreate):

keyboard.setFocusable(true);
keyboard.setFocusableInTouchMode(true);
like image 180
Shade Avatar answered May 12 '26 04:05

Shade


You can try this (In UTILITY class):

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);
     }
like image 40
Maddy Avatar answered May 12 '26 04:05

Maddy