8

I am using xamarin forms. I have designed a login form page in xaml. I want to shift the login form view upward when the keyboard appears, so that both the text field and login button is visible in case of both the platform Android and IOS. How to calculate the keyboard height and shift the Login form view upward by dynamically calculating the keyboard height.

enter image description here

Below is my xaml code :

<ContentPage>
    <ScrollView>
        <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Grid Padding="20, 30, 20, 20" RowSpacing="20" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>

                <Image Grid.Row="0" Source="login.png" HorizontalOptions="Center" VerticalOptions="Center"/>

                <Entry Grid.Row="2" x:Name="entryUserName" HorizontalOptions="Fill"  Placeholder="Username" PlaceholderColor="#707070" Text="{Binding UserName,Mode=TwoWay}" Margin="5"/>

                <BoxView Grid.Row="2" HeightRequest="1" HorizontalOptions="Fill" BackgroundColor="#707070" VerticalOptions="End"/>

                <Entry Grid.Row="3" x:Name="entryPassword" Text="{Binding Password,Mode=TwoWay}" Placeholder="Password" PlaceholderColor="#707070" Margin="5" HorizontalOptions="Fill" IsPassword="True"/>

                <BoxView Grid.Row="3" HeightRequest="1" HorizontalOptions="Fill" BackgroundColor="#707070" VerticalOptions="End"/>

                <Button Grid.Row="5" HorizontalOptions="Center" VerticalOptions="Center" Text="Login" Command="{Binding doLoginCommand}" CommandParameter="entryUserName,entryPassword" />

            </Grid>         
        </AbsoluteLayout>
    </ScrollView>
</ContentPage>

I don't want to perform any kind of custom rendering of the page. Is there any resource through which I can write the dependency service to calculate the keyboard height of different mobile view cross platform. I gone through this but it has some kind of custom rendering which I don't want.

3
  • the scrollview should automatically handle this for you
    – Jason
    Sep 22, 2016 at 14:17
  • No, scrollview doesn't shift the view upward automatically. I need to scroll, then it scrolls. I want the view to shift automcatically without scrolling. Sep 22, 2016 at 14:21
  • the scrollview should automatically adjust the view so that the textbox with focus is NOT covered by the keyboard. It may not adjust the entire view
    – Jason
    Sep 22, 2016 at 14:23

2 Answers 2

10

Option 1:

Android: Add this to your manifest:

<activity //Your MainActivity
        android:windowSoftInputMode="stateVisible|adjustResize" ... >
        ...
</activity>

Ios: Add this nuget package: https://www.nuget.org/packages/Xam.Plugins.Forms.KeyboardOverlap/

and init it:

Xamarin.Forms.Init();//platform specific init
KeyboardOverlapRenderer.Init ();

Option 2:

Add this code to your Page class:

        protected override void OnAppearing()
        {
            base.OnAppearing();
            entryUserName.Focused += InputFocused;
            entryPassword.Focused += InputFocused;
            entryUserName.Unfocused += InputUnfocused;
            entryPassword.Unfocused += InputUnfocused;
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            entryUserName.Focused -= InputFocused;
            entryPassword.Focused -= InputFocused;
            entryUserName.Unfocused -= InputUnfocused;
            entryPassword.Unfocused -= InputUnfocused;
        }
        void InputFocused(object sender, EventArgs args){
            Content.LayoutTo(new Rectangle(0,-360, Content.Bounds.Width, Content.Bounds.Height));
        }

        void InputUnfocused(object sender, EventArgs args){
            Content.LayoutTo(new Rectangle(0,0, Content.Bounds.Width, Content.Bounds.Height));
        }
2
  • I wish to calculate the height of keyboard when it appears and accordingly I want to shift my login view, so that both text field and button is visible. Is there any way to do get this. Sep 23, 2016 at 19:07
  • The LayoutTo params seems to have changed, could you update your answer by chance? Jun 23, 2017 at 20:47
2

Here is a Entry renderer to force the SoftInputMode on Android, Hope this helps:

using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Widget;
using Android.Util;
using Android.OS;
using Android.Views.InputMethods;
using System.Threading;
using Android.Views;
using Android.App;

[assembly: ExportRenderer(typeof(FormsEntry), typeof(DroidEntryRenderer))]
namespace XXX
{
    public class DroidEntryRenderer : EntryRenderer, IEntryMessages
    {
        private bool _inititialized = false;
        EditText editText;

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement != null) 
            {
                // unhook old events
            }
            if (e.NewElement != null)
            {
                // hook new events
                editText = (EditText)Control;
                var entry = e.NewElement as FormsEntry;

                (this.Element as FormsEntry).OnShowKeyboard += DroidEntryRenderer_showKeyboard;
                (this.Element as FormsEntry).OnChangeIme += DroidEntryRenderer_changeIme;

                if(entry.KeyboardInputMode == SoftInputMode.AdjustNothing)
                    (Forms.Context as Activity).Window.SetSoftInputMode(SoftInput.AdjustNothing );
                else if(entry.KeyboardInputMode == SoftInputMode.AdjustResize)
                    (Forms.Context as Activity).Window.SetSoftInputMode(SoftInput.AdjustResize );
                else
                    (Forms.Context as Activity).Window.SetSoftInputMode(SoftInput.AdjustPan );

                if(entry.SetImeToNext){
                    Control.ImeOptions = Android.Views.InputMethods.ImeAction.Next;
                    Control.SetImeActionLabel("Next", Android.Views.InputMethods.ImeAction.Next);

                    switch(entry.CustomImeAction){
                        case ImeAction.Email:
                            editText.EditorAction += (object sender, TextView.EditorActionEventArgs args) =>
                            {
                                MessagingCenter.Send<IEntryMessages>(this, "Email");
                            };
                            break;
                        case ImeAction.Password:
                            editText.EditorAction += (object sender, TextView.EditorActionEventArgs args) =>
                            {
                                MessagingCenter.Send<IEntryMessages>(this, "Password");
                            };
                            break;
                    }
                }

                if (entry.HasBorder)
                {
                    editText.SetBackgroundResource(Resource.Drawable.BorderEntry);
                }

                // edit properties
                if (entry.Font != Font.Default)
                {
                    RendererHelper.SetTextViewFont(editText, entry.Font);
                }
                if (entry.PlaceholderColor != Color.Default)
                    editText.SetHintTextColor(entry.PlaceholderColor.ToAndroid());

                switch (entry.XAlign)
                {
                case Xamarin.Forms.TextAlignment.Start:
                    editText.Gravity = Android.Views.GravityFlags.CenterVertical | Android.Views.GravityFlags.Left;
                    break;

                case Xamarin.Forms.TextAlignment.Center:
                    editText.Gravity = Android.Views.GravityFlags.Center;
                    break;

                case Xamarin.Forms.TextAlignment.End:
                    editText.Gravity = Android.Views.GravityFlags.CenterVertical | Android.Views.GravityFlags.Right;
                    editText.SetPadding(0, editText.PaddingTop, 0, editText.PaddingBottom);
                    break;
                }

                if (entry.ReturnKeyType == KeyboardType.Done)
                    editText.ImeOptions = global::Android.Views.InputMethods.ImeAction.Done;
                else if (entry.ReturnKeyType == KeyboardType.Next)
                    editText.ImeOptions = global::Android.Views.InputMethods.ImeAction.Next;

            }
        }

        void DroidEntryRenderer_showKeyboard()
        {
            ShowKeyboard();
        }

        void DroidEntryRenderer_changeIme()
        {
            ChangeIme();
        }

        public void ChangeIme(){
            Control.ImeOptions = Android.Views.InputMethods.ImeAction.Next;
            Control.SetImeActionLabel("Next", Android.Views.InputMethods.ImeAction.Next);
        }

        public void ShowKeyboard()
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                this.Control.RequestFocus();
                InputMethodManager inputMethodManager = this.Control.Context.
                GetSystemService(Android.Content.Context.InputMethodService) as InputMethodManager;
                inputMethodManager.ShowSoftInput(this.Control, ShowFlags.Forced);
                inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
            });
        }

    }
}
3
  • I wish to calculate the height of keyboard when it appears and accordingly I want to shift my view, so that both text field and button is visible. Can you give some idea. Sep 23, 2016 at 19:06
  • The system does that for you. Sep 23, 2016 at 19:27
  • No, I need to programmatically calculate the height and shift the view. The system just shift the entry cell not the whole view of my login form. I don't want to let the user scroll down for password and button field it should be visible once he touches the username entry cell Sep 24, 2016 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.