Giter Club home page Giter Club logo

keyboardvisibilityevent's Introduction

KeyboardVisibilityEvent

Android Arsenal Android Gems Maven Central

Android Library to handle soft keyboard visibility change event. show/hide keyboard method is also included.

Library's status

Currently I don't have enough time to maintain this library, so I leave this as it is.
I'm going to merge PRs when they arrive though ;)

Features

  • handle keyboard visibility change
  • check if keyboard is currently visible
  • show/hide keyboard(check UIUtil.java)

Please note that as described in this issue, currently the library cannot detect visibility change when the activity's windowSoftInputMode do not change Activity's height(such as adjustNothing).

Installation

AAR is distributed via Maven Central. The latest version is Maven Central

dependencies {
    compile 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:LATEST_VERSION'
}

Usage

check out sample project!

Add event listener for keyboard change event

Automatically unregistering the event on the Activity's onDestroy

KeyboardVisibilityEvent.setEventListener(
        getActivity(),
        new KeyboardVisibilityEventListener() {
            @Override
            public void onVisibilityChanged(boolean isOpen) {
                // some code depending on keyboard visiblity status
            }
        });

Automatically unregistering the event on the LifecycleOwner's ON_DESTROY

This is convenient when you want to KeyboardVisibilityEvent from a Fragment.

KeyboardVisibilityEvent.setEventListener(
        getActivity(),
        getLifecycleOwner(),
        new KeyboardVisibilityEventListener() {
            @Override
            public void onVisibilityChanged(boolean isOpen) {
                // some code depending on keyboard visiblity status
            }
        });

Manually unregistering the event

// get Unregistrar
Unregistrar unregistrar = KeyboardVisibilityEvent.registerEventListener(
        getActivity(),
        new KeyboardVisibilityEventListener() {
            @Override
            public void onVisibilityChanged(boolean isOpen) {
                // some code depending on keyboard visiblity status
            }
        });

// call this method when you don't need the event listener anymore
unregistrar.unregister();

License

Copyright 2015-2021 Shimizu Yasuhiro (yshrsmz)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

keyboardvisibilityevent's People

Contributors

alzhuravlev avatar anoop44 avatar bensmiley avatar braisgabin avatar kuno avatar piasy avatar starsep avatar treyshaffer avatar yshrsmz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

keyboardvisibilityevent's Issues

we need to migrate to AGP 3.2.0

Before reporting issue, please confirm your project that

  1. your Activity's windowSoftInputMode is set to the mode that actually changes Activity's height upon Keyboard visibility change.
    If windowSoftInputMode does not change Activity's height, the library can't detect Keyboard visibility change.

  2. your Keyboard is actually changing Activity's height.
    The library can't detect event when a user is using a keyboard that does not change Activity's height.

If either of these are true, It's the library's limitation. I can't help you for now.
If you come up with something nice to handle these situation, please help me :)

If neither of these are true, please tell me your issue.

You need to let me know:

  1. your Activity's windowSoftInputMode
  2. Android version
  3. Android device
  4. and other stuff you think might be helpful

IllegalStateException getContentRoot(activity).getChildAt(0) returning null

Hi there, first of all, thank you for doing this great project I really like it

lately, I have got a crash reporting from Crashlytics

Crash caused by java.lang.IllegalStateException
getContentRoot(activity).getChildAt(0) must not be null
net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent.getActivityRoot$keyboardvisibilityevent_release (KeyboardVisibilityEvent.kt:147)

in my activity, I have a fragment tag inside a parent view group which is ConstraintLayout
I am using NavigationComponent from jetpack to navigate between my fragments

I hope this will help you fix this and I promise in my free time I will try to fix it by myself
Keep the good work you really did a nice job

SOFT_INPUT_IS_FORWARD_NAVIGATION fires new IllegalArgumentException

Hi!
Thanks for your work to provide the world such a pretty library!

Nevertheless with version 2.2.1 I caught some strange behaviour, which I misunderstood.

I have some Activities with Fragments. Activities have adjustResize option enabled.
KeyboardVisibilityEvent.registerEventListener() method is called in onResume() of fragments lifecycle & is sometimes working fine, but sometimes - is not.

After debugging of this issue I gathered that activity.getWindow().getAttributes().softInputMode has SOFT_INPUT_IS_FORWARD_NAVIGATION flag sometimes included when onResume() is called, along with expected SOFT_INPUT_ADJUST_RESIZE (In other words I receive mode 274 instead of regular mode 18).
So finally I get an error:
new IllegalArgumentException("Parameter:activity window SoftInputMethod is not ADJUST_RESIZE").

If I am correct - this flag doesn't affect behaviour of the library, so could you please take this flag into consideration & make an update to the library.
Or, please, explain me, how to avoid such an error.

As a workaround I delay the call to KeyboardVisibilityEvent.registerEventListener() method by 100ms after onResume() & it works.

Not working with the activity using dialog theme

I have activity A (normal theme) register keyboard listener event. From A, I start activity B (dialog theme & register keyboard listener event too), when keyboard changed, I only receive the event on A, not on B.

Can you help me? I want to receive the event on activity B.

KeyboardVisibilityEvent Status is open on devices having big status bar

With Android 9 on some devices, the status bar height is large so the event listener for KetboardVisibilityEvent is always open.

Here is the attached screenshot of the device emulator having the big status bar:
device-2019-07-05-144756

I tried to get the values of Screen Height, Height Difference, Status Bar, etc and here are the results:

  1. ScreenHeight = 1920
  2. StatusBarHeight = 171
  3. Rectangle = Rect(0, 171 - 1080, 1794)
  4. HeightDifference = 297
  5. KeyboardMinHeight = ScreenHeight * KeyboardMinRatio = 1920*0.15 = 288

As you can see that the HeightDifference is bigger than KeyboardMinHeight. Due to this the status is always open.

I think we need to include status bar height in calculation to make it work.
Can you please check?

Let me know if you need more details

Thanks

SomeTimes not work

if the device is LandScape and the keyboard is fullScreen,it will not work.

Bottomnav blinks for a second when keyboard is closed again.

  1. your Activity's windowSoftInputMode: Adjustresize

  2. Android version: 10

  3. Android device: Pixel 3 XL API 29

  4. and other stuff you think might be helpful:

The problem I encounter is, that I am trying to hide my bottom navigation bar, but it does not work 100%. When I click on an edittext, the bottomnav is hidden and everything is fine. But when I close the keyboard, the bottom nav blinks for a second above the keyboard and this looks hideous

What am I doing wrong here?

Code:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        hideBottomNavWhenKeyboardClicked()
    }
fun Fragment.hideBottomNavWhenKeyboardClicked() {
    KeyboardVisibilityEvent.setEventListener(
        requireActivity(),
        viewLifecycleOwner,
        object : KeyboardVisibilityEventListener {
            override fun onVisibilityChanged(isOpen: Boolean) {
                if (isOpen) hideBottomNav() else showBottomNav()
            }
        }
    )
}
fun Fragment.hideBottomNav() {
    if ((requireActivity() as MainActivity).isBottomNavVisible()) (requireActivity() as MainActivity).hideBottomNav()
}

fun Fragment.showBottomNav() {
    if (!(requireActivity() as MainActivity).isBottomNavVisible()) (requireActivity() as MainActivity).showBottomNav()
}
    fun isBottomNavVisible(): Boolean {
        return binding.bottomNavigationView.visibility == View.VISIBLE
    }

Keyboard state in certain device is not accurate

Hi, I am using your library for some time and it works great, but recently one of my user report a strange behaviour.

Here are the details:

  1. Device name: Essential ph-1 phone
  2. Android version 7.1.1
  3. Use default keyboard, not custom
  4. I use windowSoftInputMode adjustResize

I use the event listener to hide a button when the keyboard is open, I think somehow this device detect the keyboard is open when it is not (the activity just started, and it don't show keyboard on start). Do you have any idea what cause this? Thanks

java.lang.RuntimeException: Failed to call observer method

Hello! Love the library, I'm just experiencing a crash while running Espresso tests.
Steps to reproduce:

  • Create a test
    @Test
    fun launchFragment(){
        launchFragmentInContainer<MyFragment>()
    }
  • Create a fragment extension to listen to the keyboard visibility events
fun Fragment.setOnKeyboardShowingListener(then: (isOpen: Boolean)-> Unit){ 
    setEventListener(
        requireActivity(),
        viewLifecycleOwner,
        object : KeyboardVisibilityEventListener {
            override fun onVisibilityChanged(isOpen: Boolean) {
                then.invoke(isOpen)
            }
        })
}
  • Add this extension to MyFragment
    setOnKeyboardShowingListener {
            if (it){
                // Do something
            }
        }
  • When espresso tests finishes, the crash seems to occur when destroying the fragment:
Caused by: java.lang.IllegalStateException: getContentRoot(activity).getChildAt(0) must not be null
at net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent.getActivityRoot$keyboardvisibilityevent_release(KeyboardVisibilityEvent.kt:147)
at net.yslibrary.android.keyboardvisibilityevent.SimpleUnregistrar.unregister(SimpleUnregistrar.kt:30)
at net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent$setEventListener$1.onDestroy(KeyboardVisibilityEvent.kt:44)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:216)

The extension is not necessary, it crashes even if I have the setEventListener directly in my fragment.
Again, I love the library, hopefully we can find a solution for this <3

米4 系统6.0测的,打开或者关闭都会多次回调方法

Before reporting issue, please confirm your project that

  1. your Activity's windowSoftInputMode is set to the mode that actually changes Activity's height upon Keyboard visibility change.
    If windowSoftInputMode does not change Activity's height, the library can't detect Keyboard visibility change.

  2. your Keyboard is actually changing Activity's height.
    The library can't detect event when a user is using a keyboard that does not change Activity's height.

If either of these are true, It's the library's limitation. I can't help you for now.
If you come up with something nice to handle these situation, please help me :)

If neither of these are true, please tell me your issue.

You need to let me know:

  1. your Activity's windowSoftInputMode
  2. Android version
  3. Android device
  4. and other stuff you think might be helpful

Possible workaround for adjustNothing

Hi there, I am using your library on my second project and its work fine, thank you. But today i needed to use adjustNothing in activity to prevent it from moving (coz was implementing custom animation). After several hours of researching I discovered the following snippet and successfully applied it to my activity: https://github.com/siebeprojects/samples-keyboardheight/blob/master/app/src/main/java/com/siebeprojects/samples/keyboardheight/KeyboardHeightProvider.java

Hope you will get some new ideas for your library =) good luck

setEventListener leaks fragment

When calling setEventListener from fragment instance the listener does not get unregistered when the fragment is destroyed. The reason is simple - this library registers activity lifecycle observer, but the activity outlives fragments.

At minimum this causes fragment leak, in worst case scenario it causes application crash in case the event listener touches dead fragment views/data bindings.

What we would like to have added is to use Architecture Components lifecycle support, so in addition to activity there would be a LifecycleOwner passed to setEventListener where you can then observe its lifecycle and unregister the listener automatically when the owner is destroyed, be it Activity or Fragment.

For now the workaround is to manually unregister the listener in corresponding Fragment's lifecycle methods.

Not working with DialogActvity

I have used windowSoftInputMode is adjustResize and my android os version 5.0 and device is Nexus 5. I am getting IsOpen true or false in normal activity. but If I use Theme.dialog for Activity means DialogActvity then its not working in my case

Readme needs Update: getLifecycleOwner(), is not an argument for setEventListener

As Described in the Readme:

KeyboardVisibilityEvent.setEventListener(
        getActivity(),
        getLifecycleOwner(),
        new KeyboardVisibilityEventListener() {
            @Override
            public void onVisibilityChanged(boolean isOpen) {
                // some code depending on keyboard visiblity status
            }
        });

LifeCycleOwner is not an option in the method. Can you please explain why it is removed?

NullPointerException when using AppCompatActivity with appcompat-v7:23.1.0

My activity is AppCompatActivity, and when I use appcompat-v7:22.2.1, activity.findViewById(android.R.id.content)
returns
android.widget.FrameLayout{1a8e3406 V.E..... ......I. 0,0-0,0 #1020002 android:id/content}
which works well.
But when I use appcompat-v7:23.1.0, activity.findViewById(android.R.id.content) returns:
android.support.v7.internal.widget.ContentFrameLayout{8337fad V.E..... ......I. 0,0-0,0 #1020002 android:id/content}
whose children are all null, causing the NPE.

Event using the keyboard

Hi

The situation is following. Application A while hanging out in the background. The user enters the SMS messages and calls the keyboard to enter the text.
Can Application A somehow receive an event about the fact of using the keyboard in SMS messages? Application A wants to get only the fact of using the keyboard, without any data.

the KeyboardVisibilityEvent is doesn't work when I use fullScreen

it can work when I not use fullScreen,my softInputMethod is normal , here is my fullScreen code:

public void applyFullScreen(boolean enable) {
        isFullScreen = enable;
        if (enable) {
            getImageView_apply_full_screen_state().setImageResource(R.drawable.push_down);
            WindowManager.LayoutParams lp = this.getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            this.getWindow().setAttributes(lp);
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            hideBottomUIMenu();
        } else {
            getImageView_apply_full_screen_state().setImageResource(R.drawable.push_up);
            WindowManager.LayoutParams attr = this.getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            this.getWindow().setAttributes(attr);
            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            showBottomUIMenu();
        }
    }

public void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

public void showBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.VISIBLE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(0);
        }
    }

currentAndroidVersion is 5.1.1
wish it‘s helpful.

Tablet Devices: not working

not working in SGH and other Tablets ...I have test and perfectly work on Samsungh Device S4, but the same example not work on SGH Tablet 7" and 10" and also Huawei and China Devices

ADJUST_RESIZE validation

Hi,

thank you for such a useful lib!

I am not sure that code below correctly check that activity has WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE

may be

WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE & softInputMethod  != 0

?
in my case softInputMethod == 275 which tells us that activity is ADJUST_RESIZE

KeyboardVisibilityEvent.java

        int softInputMethod = activity.getWindow().getAttributes().softInputMode;
        if (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED != softInputMethod &&
                (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE > softInputMethod ||
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN <= softInputMethod)) {
            throw new IllegalArgumentException("Parameter:activity window SoftInputMethod is not ADJUST_RESIZE");
        }

thisnk you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.