खोज…


जब उपयोगकर्ता स्क्रीन पर कहीं और टैप करता है तो कीबोर्ड छिपाएं

अपनी गतिविधि में कोड जोड़ें।

यह Fragment के लिए भी काम करेगा, Fragment में इस कोड को जोड़ने की कोई आवश्यकता नहीं है

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
        ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

कीबोर्ड को खोलने और बंद करने के लिए कॉलबैक रजिस्टर करें

विचार प्रत्येक परिवर्तन से पहले और बाद में एक लेआउट को मापने के लिए है और अगर कोई महत्वपूर्ण बदलाव है तो आप कुछ हद तक निश्चित हो सकते हैं कि इसका सॉफ्टकबोर्ड।

// A variable to hold the last content layout hight
private int mLastContentHeight = 0;

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override public void onGlobalLayout() {
        int currentContentHeight = findViewById(Window.ID_ANDROID_CONTENT).getHeight();

        if (mLastContentHeight > currentContentHeight + 100) {
            Timber.d("onGlobalLayout: Keyboard is open");
            mLastContentHeight = currentContentHeight;
        } else if (currentContentHeight > mLastContentHeight + 100) {
            Timber.d("onGlobalLayout: Keyboard is closed");
            mLastContentHeight = currentContentHeight;
        }
    }
};

फिर हमारे में onCreate के लिए प्रारंभिक मान सेट mLastContentHeight

mLastContentHeight = findViewById(Window.ID_ANDROID_CONTENT).getHeight();

और श्रोता जोड़ें

rootView.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

destroy पर श्रोता को हटाने के लिए मत भूलना

rootView.getViewTreeObserver().removeOnGlobalLayoutListener(keyboardLayoutListener);


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow