0

I have a login form with edittexts and a login button(connect). When a user click the edittexts the keyboard opens, and when they click the login button(connect) they keyboard disappears. The problem is if a user clicks on a edittext after clicking the login button, the keyboard shows for a second, then dissapears. Using rootview to calculate if the keyboard is showing or not, since that seems to be the easiest way according to stackoverflow. How do i make it so the keyboard can be shown after clicking the button?

Onclicklistener

boolean clicked=false;

        connect.setOnClickListener(v -> {


        clicked=true;
        keyboard();

    });

keyboard method

    void keyboard(){

    InputMethodManager inputManager = (InputMethodManager)
            getSystemService(Context.INPUT_METHOD_SERVICE);

        final View activityRootView = findViewById(R.id.wrap);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(r);

                if (clicked) {
                    int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                    if (heightDiff > 0.25 * activityRootView.getRootView().getHeight()) {
                        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        });


}
Tom
  • 47
  • 6

1 Answers1

0

Your onGlobalLayout listener is called with each layout update, which will lead the keyboard to be dismissed after each layout update if the button was clicked once i don't really get what you're trying to do there and why are you doing this check

if (heightDiff > 0.25 * activityRootView.getRootView().getHeight())

You could simply dismiss the keyboard directly in your ButtonClickListener

connect.setOnClickListener(v -> { 
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);        });
Muhannad Fakhouri
  • 1,468
  • 11
  • 14
  • woooow. thanks..I approached this waaay to complicated. the heightdiff was used to determing if the keyboard is showing. Using this post: https://stackoverflow.com/questions/3568919/android-how-can-i-tell-if-the-soft-keyboard-is-showing-or-not – Tom Mar 25 '20 at 20:00