Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Soft Keyboard does not Pop Up when Entry View's Focus is set to True Programmatically #5983

Closed
Tracked by #11703
cbaer-extron opened this issue Apr 11, 2022 · 26 comments · Fixed by #12890, #13824 or #13908
Closed
Tracked by #11703
Assignees
Labels
area-controls-entry Entry fixed-in-7.0.81 Look for this fix in 7.0.81! fixed-in-7.0.92 Look for this fix in 7.0.92! fixed-in-7.0.100 fixed-in-7.0.101 fixed-in-8.0.0-preview.3.8149 Look for this fix in 8.0.0-preview.3.8149! fixed-in-8.0.0-preview.4.8333 Look for this fix in 8.0.0-preview.4.8333! migration-compatibility Xamarin.Forms to .NET MAUI Migration, Upgrade Assistant, Try-Convert p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint platform/android 🤖 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working

Comments

@cbaer-extron
Copy link

cbaer-extron commented Apr 11, 2022

Description

When Focus is set to an Entry view programmatically (entryTest.Focus()), the cursor blinks in the edit field of the Entry view, but the soft keyboard does not pop up as it should until you physically touch the Entry view. In comparison to Xamarin Forms where the keyboard pops up when executing entryTest.Focus().

Also, entryTest.Focus() is ignored when placed in the OnAppearing Event.

Video demo of Maui App:

SetFocusMaui.mp4

Video demo of Xamarin Forms version:

SetFocusXF.mp4

XAML:
image

Code Behind:
image

Steps to Reproduce

  1. Create a new blank Maui app
  2. Add and Entry View and name it entryTest
  3. Add 2 Buttons and set Text to "Set Focus" and "Set Unfocus"
  4. In the Code behind for the 1st button add code entryTest.Focus()
  5. In the Code behind for the 2nd button add code enryTest.Unfocus()
  6. Run the App
  7. Click the Set Focus button.
  8. Notice the Entry field cursor blinks
  9. Notice the keyboard does not pop up
  10. Tap the Entry field.
  11. Notice the keyboard pops up.

Version with bug

Preview 14 (current)

Last version that worked well

Unknown/Other

Affected platforms

Android

Affected platform versions

Android 11

Did you find any workaround?

Workaround

I added a mapper here that you can copy to add this behavior for android.

One thing to note is that if your intention is to open the keyboard you should use
KeyboardManager.ShowKeyboard not Focus

Using Focus to influence the Keyboard has always felt like a hack to me in general.

Relevant log output

No response

@cbaer-extron cbaer-extron added s/needs-verification Indicates that this issue needs initial verification before further triage will happen t/bug Something isn't working labels Apr 11, 2022
@XamlTest XamlTest added s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage and removed s/needs-verification Indicates that this issue needs initial verification before further triage will happen labels Apr 12, 2022
@XamlTest
Copy link

Verified this issue with Visual Studio Enterprise 17.2.0 Preview 2.1 [32317.152]. Repro on Android. Sample Project: 5983.zip

@jsuarezruiz jsuarezruiz self-assigned this Apr 12, 2022
@ghost ghost added the legacy-area-controls Label, Button, CheckBox, Slider, Stepper, Switch, Picker, Entry, Editor label Apr 12, 2022
@jsuarezruiz jsuarezruiz added this to the 6.0.300-rc.2 milestone Apr 18, 2022
@SailDev
Copy link

SailDev commented Jun 26, 2022

Still not working in GA.
Is there a method, to show/hide the ENTRY keyboard manually?

@tataelm
Copy link

tataelm commented Jun 28, 2022

I've encountered the same problem. But when I use "Entry" inside Grid instead of StackLayout, it works just fine. Entry and StackLayout don't get along yet.

@marcoablanco
Copy link

Still not working in GA. Is there a method, to show/hide the ENTRY keyboard manually?

I've encountered a different problem. Keyboard is not hiding when unfocus entry. I made a wordaround in handler:

protected override void ConnectHandler(AppCompatEditText platformView)
{
	base.ConnectHandler(platformView);

	if (VirtualView is Entry entryControl)
		entryControl.ObserveUnfocused().Subscribe(UnfocusedSubscription);
}

private void UnfocusedSubscription(FocusEventArgs args)
{
	if (!args.IsFocused)
	{
		InputMethodManager inputMethodManager = (InputMethodManager)global::Android.App.Application.Context.GetSystemService(global::Android.Content.Context.InputMethodService);
		inputMethodManager.HideSoftInputFromWindow(PlatformView.WindowToken, HideSoftInputFlags.None);
	}
}

I use own observable method, but you can use events.

@SailDev
Copy link

SailDev commented Aug 11, 2022

Many thanks marcoablanco.
That looks interesting and a real benefit, compared to XF Forms. It seems, that i should investigate some time, understanding the handler architecture in Maui.

@SokoFromNZ
Copy link

SokoFromNZ commented Aug 13, 2022

Still not working in GA. Is there a method, to show/hide the ENTRY keyboard manually?

I've encountered a different problem. Keyboard is not hiding when unfocus entry. I made a wordaround in handler:

protected override void ConnectHandler(AppCompatEditText platformView)
{
	base.ConnectHandler(platformView);

	if (VirtualView is Entry entryControl)
		entryControl.ObserveUnfocused().Subscribe(UnfocusedSubscription);
}

private void UnfocusedSubscription(FocusEventArgs args)
{
	if (!args.IsFocused)
	{
		InputMethodManager inputMethodManager = (InputMethodManager)global::Android.App.Application.Context.GetSystemService(global::Android.Content.Context.InputMethodService);
		inputMethodManager.HideSoftInputFromWindow(PlatformView.WindowToken, HideSoftInputFlags.None);
	}
}

I use own observable method, but you can use events.

Can you give me more context how to use this in a sample app. I cannot figure out where I put these code of yours...
I've found https://github.com/davidortinau/CustomRendererSample example. But this does not work with the current MAUI version (I get a cast exception when I start the example as is).
thanks

@marcoablanco
Copy link

Still not working in GA. Is there a method, to show/hide the ENTRY keyboard manually?

I've encountered a different problem. Keyboard is not hiding when unfocus entry. I made a wordaround in handler:

protected override void ConnectHandler(AppCompatEditText platformView)
{
	base.ConnectHandler(platformView);

	if (VirtualView is Entry entryControl)
		entryControl.ObserveUnfocused().Subscribe(UnfocusedSubscription);
}

private void UnfocusedSubscription(FocusEventArgs args)
{
	if (!args.IsFocused)
	{
		InputMethodManager inputMethodManager = (InputMethodManager)global::Android.App.Application.Context.GetSystemService(global::Android.Content.Context.InputMethodService);
		inputMethodManager.HideSoftInputFromWindow(PlatformView.WindowToken, HideSoftInputFlags.None);
	}
}

I use own observable method, but you can use events.

Can you give me more context how to use this in a sample app. I cannot figure out where I put these code of yours... I've found https://github.com/davidortinau/CustomRendererSample example. But this does not work with the current MAUI version (I get a cast exception when I start the example as is). thanks

I created a EntryHandler for Maui Entry control in Android folder. You can see more about Handler in https://docs.microsoft.com/dotnet/maui/user-interface/handlers/customize

@RonnyRos
Copy link

RonnyRos commented Aug 17, 2022

Adding
<Entry Text="HELLO" Focused="Entry_Focused" Unfocused="Entry_Unfocused" />
and running it on a Android OS never triggers Entry Unfocused, with a standard maui template when tapping outside the entrybox.
Also the custom handlers does not seem to contain the following code in, or im doing it wrong: .ObserveUnfocused().Subscribe(UnfocusedSubscription);
So im not sure how you were able to run that code @marcoablanco

It just dont fire on unfocused.

@RonnyRos
Copy link

Defocus_issue.zip
Added a sample

@marcoablanco
Copy link

marcoablanco commented Aug 18, 2022

Defocus_issue.zip
Added a sample

Your handler is not registered. I added to MauiProgram and works.

		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
#if ANDROID
			.ConfigureMauiHandlers(handlers => handlers.AddHandler<Microsoft.Maui.Controls.Entry, Survey.Handlers.EntryHandler>())
#endif
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
				fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
			});

		return builder.Build();

I changed a little bit your handler

public partial class EntryHandler : Microsoft.Maui.Handlers.EntryHandler
{
	protected override void ConnectHandler(AppCompatEditText platformView)
	{
		base.ConnectHandler(platformView);
		platformView.FocusChange += PlatformView_FocusChange;
	}

	protected override void DisconnectHandler(AppCompatEditText platformView)
	{
		base.DisconnectHandler(platformView);
		platformView.FocusChange -= PlatformView_FocusChange;
	}

	private void PlatformView_FocusChange(object sender, Android.Views.View.FocusChangeEventArgs args)
	{
		if (args.HasFocus)
		{
			InputMethodManager inputMethodManager = (InputMethodManager)global::Android.App.Application.Context.GetSystemService(global::Android.Content.Context.InputMethodService);
			inputMethodManager.ShowSoftInput(PlatformView, ShowFlags.Forced);
		}
		else
		{
			InputMethodManager inputMethodManager = (InputMethodManager)global::Android.App.Application.Context.GetSystemService(global::Android.Content.Context.InputMethodService);
			inputMethodManager.HideSoftInputFromWindow(PlatformView.WindowToken, HideSoftInputFlags.None);
		}
	}
}

@RonnyRos
Copy link

RonnyRos commented Aug 19, 2022

Thank you for tweaking the sample, looks much better!

Im still struggling to make the sample work, it does not lose focus.
Meaning, when you have a entry and you click outside the entry or click a button, the entry should lose focus and stop blinking which it does not in a simple .NET maui start template.
That means as far as i can understand that this code will not run as the focuschange event will never fire when you click outside the entrybox.

I hope there are things here i dont understand .. :)

@RonnyRos
Copy link

RonnyRos commented Aug 26, 2022

Use something like this to have the old XF tap outside of the entry defocus in the mainactivity.
I think it works, might need some adjustments.


public override bool DispatchTouchEvent(MotionEvent ev)
{
    if (ev.Action == MotionEventActions.Up)
    {
        var v = Window.CurrentFocus;

        if (v is EditText)
        {
            Rect outRect = new Rect();
            v.GetGlobalVisibleRect(outRect);

            if (!outRect.Contains(new Rect(ev.RawX, ev.RawY, 1, 1)))
            {
                v.ClearFocus();
                InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
                imm.HideSoftInputFromWindow(v.WindowToken, 0);
            }
        }
    }
    return base.DispatchTouchEvent(ev);
}

@Redth Redth modified the milestones: 6.0-servicing, 7.0-rc2 Aug 30, 2022
@Redth Redth modified the milestones: 7.0-rc2, .NET 7 Planning Sep 14, 2022
@Samirgc
Copy link

Samirgc commented Oct 11, 2022

Surprised to see ! It isn't working till today.

@nickidentivue
Copy link

Try adding this code to the Focused event of the Entry. Resolved the issue of the keyboard not showing up in my MAUI app when running on Surface Pro 9. CoreInputView.GetForCurrentView().TryShow(CoreInputViewKind.Keyboard);

Found from https://stackoverflow.com/questions/39618127/programmatically-open-on-screen-keyboard-in-uwp

I can confirm this works when called from Windows platform code, I came across the same link as @relecon and chanced my arm. Added a more detailed explanation here:

(microsoft/microsoft-ui-xaml#6291)

@PureWeen
Copy link
Member

PureWeen commented Feb 16, 2023

I added a mapper here that you can copy to add this behavior for android.

One thing to note is that if your intention is to open the keyboard you should use
KeyboardManager.ShowKeyboard not Focus

Using Focus to influence the Keyboard has always felt like a hack to me in general.

@Sourcephy
Copy link

Try this solution

`private async void OnShowKeyboardTapped(object sender, EventArgs e)
{
EntryInput.Focus();
await Task.Delay(100); // Important to add delay here
Helpers.KeyboardVisibility(true);
}

private async void OnHideKeyboardTapped(object sender, EventArgs e)
{
Helpers.KeyboardVisibility(false);
}

private void KeyboardVisibility(bool StateFocus)
{
#if ANDROID
if (Platform.CurrentActivity.CurrentFocus != null)
{
if (StateFocus)
{
Platform.CurrentActivity.ShowKeyboard(Platform.CurrentActivity.CurrentFocus);
}
else
{
Platform.CurrentActivity.HideKeyboard(Platform.CurrentActivity.CurrentFocus);
Platform.CurrentActivity.CurrentFocus.ClearFocus();
}
}
#endif
}
`

PureWeen added a commit that referenced this issue Mar 9, 2023
### Description of Change

Show keyboard on Android entry/editor/searchbar focus

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #5983

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
@github-project-automation github-project-automation bot moved this from In Progress to Done in MAUI SDK Ongoing Mar 9, 2023
rachelkang pushed a commit that referenced this issue Mar 9, 2023
Show keyboard on Android entry/editor/searchbar focus

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes #5983

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->
@samhouts samhouts added fixed-in-7.0.81 Look for this fix in 7.0.81! fixed-in-8.0.0-preview.3.8149 Look for this fix in 8.0.0-preview.3.8149! labels Apr 12, 2023
@ghost ghost locked as resolved and limited conversation to collaborators May 12, 2023
@samhouts samhouts added the fixed-in-8.0.0-preview.4.8333 Look for this fix in 8.0.0-preview.4.8333! label Jun 8, 2023
@samhouts samhouts added the fixed-in-7.0.92 Look for this fix in 7.0.92! label Jul 11, 2023
@samhouts samhouts added the migration-compatibility Xamarin.Forms to .NET MAUI Migration, Upgrade Assistant, Try-Convert label Aug 28, 2023
@Eilon Eilon removed the legacy-area-controls Label, Button, CheckBox, Slider, Stepper, Switch, Picker, Entry, Editor label May 10, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-controls-entry Entry fixed-in-7.0.81 Look for this fix in 7.0.81! fixed-in-7.0.92 Look for this fix in 7.0.92! fixed-in-7.0.100 fixed-in-7.0.101 fixed-in-8.0.0-preview.3.8149 Look for this fix in 8.0.0-preview.3.8149! fixed-in-8.0.0-preview.4.8333 Look for this fix in 8.0.0-preview.4.8333! migration-compatibility Xamarin.Forms to .NET MAUI Migration, Upgrade Assistant, Try-Convert p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint platform/android 🤖 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Projects
None yet