How can i set the focus ( and display the keyboard ) on Entry control.

Hi,

How can i set the focus ( and display the keyboard ) on Entry control in Xamarin forms.

Posts

  • NikhileshParmarNikhileshParmar USMember ✭✭

    Hi Adam,

    But it's not working.

    I tried with below code.

    Entry txtUserName = new Entry();
    txtUserName.Focus();

    But doesn't set focus and not open keyboard also.

  • NikhileshParmarNikhileshParmar USMember ✭✭

    We’ve implemented a login screen at the start of the app. When the app starts it focusing on the username textbox and opens the keyboard in login screen.

    We’ve recently updated our xamarin forms version to 1.3.4 . After updating xamarin forms keyboard is not opening on focus method. We already called focus method in OnAppearing event of the page. But this thing is working fine when we click logout button and goes to login page it opens the keyboard.

    Below is the sample code that we are using to focus on textbox and open a keyboard.

    protected override void OnAppearing()
    {
    txtUserName.Focus();
    }

    So can you please let us know what is the issue with the opening a keyboard on textbox focus method when app starts.

  • FranciscoGGFranciscoGG ESMember ✭✭
    edited June 2015

    And how could I set the focus from a ViewModel?

  • NMackayNMackay GBInsider, University mod
    edited June 2015

    @Francisco.7655

    I usually use send a message to the view to tell it to do the focus.

    ViewModel

    public RelayCommand SearchCommand { get { return _searchCommand ?? (_searchCommand = new RelayCommand( async () => { try { // Dismiss the keyboard Messenger.Default.Send(new SetKeybrdVisibilityMsg { PageName = ViewModelLocator.PageKeySearch, Show = false });

    View:

    `
    namespace CustomerFinder.View
    {
    public partial class SearchPage : IPageLifetime
    {
    public SearchPage()
    {
    InitializeComponent();

            Messenger.Default.Register<SetKeybrdVisibilityMsg>(this, action =>
            {
                if (!Equals(action.PageName, ViewModelLocator.PageKeySearch))
                {
                    return;
                }
    
                if (action.Show)
                    EntryCustName.Focus();
                else
                    EntryCustName.Unfocus();
            });
        }
    
        public void CleanupPage()
        {
            Messenger.Default.Unregister<SetKeybrdVisibilityMsg>(this);
            // Cancel data fetch
            ((SearchViewModel) BindingContext).Cleanup();
            SimpleIoc.Default.Unregister<SearchViewModel>();
        }
    
        protected override void OnAppearing()
        {
            base.OnAppearing();
            if (((SearchViewModel) BindingContext).Customers.Count == 0)
                EntryCustName.Focus();
        }
    }
    

    }
    `

  • AndrewMobileAndrewMobile USMember ✭✭✭✭

    wouldn't be much simpler if you added a Click event handler in the code-behind and call Focus() \ UnFocus() on the Entry based on some public property which is a state in the view-model?
    or, you could even use triggers right in XAML

  • NMackayNMackay GBInsider, University mod

    That's another approach but I don't like having VM properties which are only for view control purposes, just showing a different approach.

  • AndrewMobileAndrewMobile USMember ✭✭✭✭

    sure, not trying to start a debate here just trying to share my opinion
    but aren't public VM properties for views?

  • AndrewMobileAndrewMobile USMember ✭✭✭✭

    just my humble opinion: using Messenger seems too much for that task

  • NMackayNMackay GBInsider, University mod

    @AndreiNitescu

    Two topic's that seem to generate endless debate are MVVM and ORM vs stored procedures and direct SQL in my experience (ORM is my preference...LLBLGen) :smile:

    I generally use value convertors to set state of UI elements etc, I've seen people use properties mixed up with data properties in collections to set colors in a list etc, don't agree with that.

    it just depends how far you want to take SoC between view and view model, what your suggesting is fine and sometimes a better approach, I just found this worked well and reliably as the entry fires the Command on the completed event. I tried other approaches at the time but this code was written back in forms 1.2.3 and I haven't visited it since so there may be a nicer way, I just don't like cluttering up my VM with properties for UI support, I try and have it expose, data binding properties and commands where possible. There is a common sense element that has to be applied though.

  • AndrewMobileAndrewMobile USMember ✭✭✭✭
    edited June 2015

    I generally use value convertors to set state of UI elements etc, I've seen people use properties mixed up with data properties in collections to set colors in a list etc, don't agree with that.

    I also use converters. Any UI related data including Color shouldn't appear in a VM.

    I just don't like cluttering up my VM with properties for UI support,

    I didn't mean to suggest you should expose a property in VM just for the sake of hacking around something in the UI.
    For this kind of UI things, I'm trying to use code-behind of the Page (event handlers of the controls) or even triggers in XAML if possible. If that's not really possible or if something else is really more appropriate, I would still use a service instead of Messenger. But there are cases when Messenger is just easier. This is just my opinion...

  • adamkempadamkemp USInsider, Developer Group Leader mod

    The entire purpose of a view model is for adapting things for use by the view. That's why it has "view" in the name. Otherwise you would just use the model.

    It is completely acceptable and a normal practice to have properties in the view model that exist solely to make it easier to do things in the view with less code. After all, code in the view model is portable and reusable and testable so you may be saving yourself some work.

    Value converters are great when they're sufficient, but when they're not it seems unreasonable to me to refuse to add any properties to a view model for use by the view. There's no other reason to have the view model of not for that.

  • AnkurAnkur USMember ✭✭

    When setting Focus, the Keyboard transitions from shown->hidden->shown again.
    What we really need is to keep it shown without intermediate hidden. Is there anyway we can achieve this? If not cross-platform, is there something custom that can be done for android?

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @adamkemp said:
    The entire purpose of a view model is for adapting things for use by the view. That's why it has "view" in the name. Otherwise you would just use the model.

    It is completely acceptable and a normal practice to have properties in the view model that exist solely to make it easier to do things in the view with less code. After all, code in the view model is portable and reusable and testable so you may be saving yourself some work.

    Value converters are great when they're sufficient, but when they're not it seems unreasonable to me to refuse to add any properties to a view model for use by the view. There's no other reason to have the view model of not for that.

    Yes and no. A view model exists to be a backing for one OR MORE views. It is commonly an amalgamation of multiple models, giving the View all of the data it needs. That's why you can't use just a model.

    If you have EmployeeViewModel, it can back any view that displays an Employee object: NOT just one specific view. It might include models for Employee, Job, Location, Schedule. Put them all together and you get everything a view needs when displaying an Employee.

    If the current view is the SupervisorView it might have a given UI control because the supervisor is allowed to change that Employee.Password. But if the current view is the HumanResourceView it would have different controls even though both views are currently looking at the same EmployeeViewModel looking at the same CurrentEmployee.

    So a ViewModel should NOT every actually know about or depend on elements in the UI layout. That's not the direction of the relationship. The ViewModel is still just data and actions, without knowledge of the GUI.

    So in the case of this original question... It would be really nice to have a .HasFocus property on a GUI element that you can bind to a property in the ViewModel. An example of that use would be along the lines of.
    Entry Password.HasFocus {binding Username, converter NotNullConverter}
    In this case we could have the password box receive focus, and thus open the keyboard, once the username has been set. That's kind of the typical behavior users expect: Set the username and have focus jump to the password.

  • adamkempadamkemp USInsider, Developer Group Leader mod

    So a ViewModel should NOT every actually know about or depend on elements in the UI layout.

    That's correct.

    The ViewModel is still just data and actions, without knowledge of the GUI.

    That's incorrect.

    A view model shouldn't know about any view types, but (again) the purpose of a view model is to model the view. If there's a particular view that needs a particular bit of logic or information from the view model then you should add that to the view model, even if no other view needs it. That's the whole purpose of the view model.

    There may be cases like you described where you want a view model type to be usable by multiple view types. That's ok. It just shouldn't be a requirement.

    Let me put it another way just to be clear. If your view model is designed in such a way that you can't replace the view layer implementation (say, switching from Android to iOS) then that's wrong. But if you change what information is displayed in a view or how a view behaves then it is acceptable and common to need to change the view model.

    The view model represents the state and behavior of the view in an implementation-agnostic way. Of course there are going to be cases where bits of logic in a view model are specific to one particular part of the UI in your application, and those bits of logic may not be necessary for any other part of the application. They could be used elsewhere, but they don't need to be used everywhere that view model could conceivably be used in order to be proper. Don't limit yourself to constructing a dumb model layer. You're just going to end up having to put more logic in your view layer as a result, and that's the opposite of what you want.

    As long as you can swap out the implementation of the view and keep the same view model you're still doing it right.

  • PhilippSumiPhilippSumi USMember ✭✭✭

    I was pulling my hair out on this when trying to (re-)set focus after a tap on an icon. Turns out an easy solution is to just explicitly unfocus the entry - in that case, the subsequent focus seems to do the trick:

            var tapRecognier = new TapGestureRecognizer();
            MyIconControl.GestureRecognizers.Add(tapRecognier );
            tapRecognier.Tapped += (s, e) =>
            {
                //Xamarin only seems to set focus properly if it's removed first...
                Entry.Unfocus();
                Text = "";
                Entry.Focus();
            };
    

    Verified only on Android so far...

  • ElPiponElPipon COMember ✭✭

    @PhilippSumi Can show me how you use this?

  • MatthewSnyderMatthewSnyder USMember ✭✭

    @adamkemp said:

    So a ViewModel should NOT every actually know about or depend on elements in the UI layout.

    That's correct.

    The ViewModel is still just data and actions, without knowledge of the GUI.

    That's incorrect.

    A view model shouldn't know about any view types, but (again) the purpose of a view model is to model the view. If there's a particular view that needs a particular bit of logic or information from the view model then you should add that to the view model, even if no other view needs it. That's the whole purpose of the view model.

    There may be cases like you described where you want a view model type to be usable by multiple view types. That's ok. It just shouldn't be a requirement.

    Let me put it another way just to be clear. If your view model is designed in such a way that you can't replace the view layer implementation (say, switching from Android to iOS) then that's wrong. But if you change what information is displayed in a view or how a view behaves then it is acceptable and common to need to change the view model.

    The view model represents the state and behavior of the view in an implementation-agnostic way. Of course there are going to be cases where bits of logic in a view model are specific to one particular part of the UI in your application, and those bits of logic may not be necessary for any other part of the application. They could be used elsewhere, but they don't need to be used everywhere that view model could conceivably be used in order to be proper. Don't limit yourself to constructing a dumb model layer. You're just going to end up having to put more logic in your view layer as a result, and that's the opposite of what you want.

    As long as you can swap out the implementation of the view and keep the same view model you're still doing it right.

    Great explanation Adam!

  • Ashish_sharmaAshish_sharma INMember ✭✭✭

    hello guy's , i have a popup and in this popup there is one label and one entry control and two button like cancel and save button , now i tap in entry control for write something on it and keyboard is open now i type on it , then i press a save button popup get hide ( now this time keyboard is open already ) , now i close a keyboard and clicked save button it work. why this happening i don't know but i saw when i open keyboard popup get hide but there control is showing , any idea why it happen tell me how to solve this problem for all platforms

    Thank's in Advance,

  • Ashish_sharmaAshish_sharma INMember ✭✭✭

    @DanielMay said:
    Nikhilesh, Have you added that Entry to an actual form?

    This works fine for me:

        public static Page GetMainPage()
      {
          var myEntry = new Entry ();
    
          var contentPage = new ContentPage {
              Content = myEntry
          };
    
          contentPage.Appearing += (object sender, System.EventArgs e) => myEntry.Focus ();
    
          return contentPage;
      }
    

    Have any example for tath

Sign In or Register to comment.