FocusChange After Opening Keyboard

Nathan Sokalski 4,121 Reputation points
2021-11-21T22:22:15.307+00:00

As we know, the keyboard is usually displayed when an EditText receives focus or is tapped. This is what I want, however, I have a layout change that I need to do AFTER the keyboard is opened (because it depends on the available space). But because FocusChange is called before the keyboard is displayed, I need a way to detect when the keyboard has been opened. I thought about using the LayoutChange event, but that would make it much harder to do some of the things I do in FocusChange, not to mention it would probably end up getting triggered at undesired times. Is there a way to detect when the keyboard has finished opening?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,297 questions
0 comments No comments
{count} votes

Accepted answer
  1. JarvanZhang 23,951 Reputation points
    2021-11-22T06:42:20.733+00:00

    Hello njsokalski,​

    Welcome to our Microsoft Q&A platform!

    To check whether the keyboard is open, try adding OnLayoutChangeListener for the root layout of the Activity. If the height of the Activity pushed up exceeds 1/3 of the screen height, we can conside the soft keyboard has popped up.

    Here is the sample code, you could refer to it.

       public class TestActivity : AppCompatActivity, View.IOnLayoutChangeListener  
       {  
           protected override void OnCreate(Bundle savedInstanceState)  
           {  
               ...  
         
               var layout = FindViewById<RelativeLayout>(Resource.Id.root);  
               keyHeight = this.WindowManager.DefaultDisplay.Height / 3;  
               layout.AddOnLayoutChangeListener(this);  
           }  
         
           int keyHeight = 0;  
           public void OnLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)  
           {  
               //If the height of the activity pushed up exceeds 1/3 of the screen height, the soft keyboard can be considered to be up  
               if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight))  
               {  
                   //the keyboard is open  
               }  
               else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight))  
               {  
                   //the keyboard is closed  
               }  
           }  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful