Xamarin Android窗口软输入调整大小(特定页面)

lo8azlld  于 2022-12-07  发布在  Android
关注(0)|答案(2)|浏览(157)

有没有办法将Android.Views.SoftInput.AdjustResize实现到特定的页面/控件(例如网格),而不是将其插入到App.xaml.csMainActivity.cs中?因为当键盘显示时,它会影响我的其他页面。
谢谢你!

nkhmeac6

nkhmeac61#

我已经解决了我的问题。我所做的是在我的page.xaml.cs上实现

protected override void OnAppearing()
{
    base.OnAppearing();
    App.Current.On<Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
}

这将在页面显示时显示键盘时调整窗口的大小,如果您希望保留Entry或其他元素的正常行为,请使用以下代码:

protected override void OnDisappearing()
{
    base.OnDisappearing();
    App.Current.On<Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Pan);
}

WindowSoftInputModeAdjust.Pan是Android在显示键盘时的默认行为。这样当页面消失时,设置将恢复为默认值。

6l7fqoea

6l7fqoea2#

作为对@jbtamares解决方案的补充,我创建了一个扩展方法,它允许在受影响的页面消失后轻松地恢复到原来的调整大小模式。
一旦在页面上呼叫UseWindowSoftInputModeAdjust,扩充方法就会追踪原始的调整大小模式。ResetWindowSoftInputModeAdjust会读取原始的调整大小模式,并进行相应的设定。

这是扩展方法的代码:

public static class PageExtensions
{
    private static readonly IDictionary<Type, WindowSoftInputModeAdjust> OriginalWindowSoftInputModeAdjusts = new Dictionary<Type, WindowSoftInputModeAdjust>();
    
    public static void UseWindowSoftInputModeAdjust(this Page page, WindowSoftInputModeAdjust windowSoftInputModeAdjust)
    {
        var platformElementConfiguration = Xamarin.Forms.Application.Current.On<Android>();
        
        var pageType = page.GetType();
        if (!OriginalWindowSoftInputModeAdjusts.ContainsKey(pageType))
        {
            var originalWindowSoftInputModeAdjust = platformElementConfiguration.GetWindowSoftInputModeAdjust();
            OriginalWindowSoftInputModeAdjusts.Add(pageType, originalWindowSoftInputModeAdjust);
        }
        
        platformElementConfiguration.UseWindowSoftInputModeAdjust(windowSoftInputModeAdjust);
    }
    
    public static void ResetWindowSoftInputModeAdjust(this Page page)
    {
        var pageType = page.GetType();
        
        if (OriginalWindowSoftInputModeAdjusts.TryGetValue(pageType, out var originalWindowSoftInputModeAdjust))
        {
            OriginalWindowSoftInputModeAdjusts.Remove(pageType);
            
            var platformElementConfiguration = Xamarin.Forms.Application.Current.On<Android>();
            platformElementConfiguration.UseWindowSoftInputModeAdjust(originalWindowSoftInputModeAdjust);
        }
    }
}

以下是如何在页面中应用它:

public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        
        this.UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        
        this.ResetWindowSoftInputModeAdjust();
    }
}

希望这能有所帮助。如果你发现上面贴出的代码有任何问题,请告诉我。

相关问题