summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.Android/KeyboardManager.cs
blob: e89ed9efd111c3977ed050cf6424c88a052ec76c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using Android.Content;
using Android.OS;
using Android.Views.InputMethods;
using Android.Widget;
using AView = Android.Views.View;

namespace Xamarin.Forms.Platform.Android
{
	internal static class KeyboardManager
	{
		internal static void HideKeyboard(this AView inputView, bool overrideValidation = false)
		{
			if (Forms.Context == null)
				throw new InvalidOperationException("Call Forms.Init() before HideKeyboard");

			if (inputView == null)
				throw new ArgumentNullException(nameof(inputView) + " must be set before the keyboard can be hidden.");

			using (var inputMethodManager = (InputMethodManager)Forms.Context.GetSystemService(Context.InputMethodService))
			{
				if (!overrideValidation && !(inputView is EditText || inputView is TextView || inputView is SearchView))
					throw new ArgumentException("inputView should be of type EditText, SearchView, or TextView");

				IBinder windowToken = inputView.WindowToken;
				if (windowToken != null && inputMethodManager != null)
					inputMethodManager.HideSoftInputFromWindow(windowToken, HideSoftInputFlags.None);
			}
		}

		internal static void ShowKeyboard(this AView inputView)
		{
			if (Forms.Context == null)
				throw new InvalidOperationException("Call Forms.Init() before ShowKeyboard");

			if (inputView == null)
				throw new ArgumentNullException(nameof(inputView) + " must be set before the keyboard can be shown.");

			using (var inputMethodManager = (InputMethodManager)Forms.Context.GetSystemService(Context.InputMethodService))
			{
				if (inputView is EditText || inputView is TextView || inputView is SearchView)
				{
					if (inputMethodManager != null) {
						inputMethodManager.ShowSoftInput(inputView, ShowFlags.Forced);
						inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
					}
				}
				else
					throw new ArgumentException("inputView should be of type EditText, SearchView, or TextView");
			}
		}
	}
}