Maintaining EditText Cursor Position

njsokalskinjsokalski Member ✭✭✭

I want to maintain the cursor position of the EditText(s) that I have in a RecyclerView. I want to do this to restore them for when the app goes to sleep, as well as when returning from certain other Activity(s) & scenarios. How do I do this? Thanks.

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited January 16

    1.Try to override OnSaveInstanceState and OnRestoreInstanceState methods to keep the view interface state.

    protected override void OnSaveInstanceState(Bundle outState)
    {
        base.OnSaveInstanceState(outState);
    }
    
    protected override void OnRestoreInstanceState(Bundle savedInstanceState)
    {
        base.OnRestoreInstanceState(savedInstanceState);
    }
    

    Tutorial:
    https://www.techotopia.com/index.php/Saving_and_Restoring_the_User_Interface_State_of_an_Android_Activity
    https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/activity-lifecycle/saving-state

    2.Or you can set the LaunchMode of the activty to LaunchMode.SingleInstance, the activity will only has one instance.

  • njsokalskinjsokalski Member ✭✭✭

    I'm not sure what you mean. Because the EditText(s) are parts of the items in the RecyclerView, I need to set the cursor position in the Adapter. The items get recreated when the page is loaded (or the View gets recycled by the RecyclerView while scrolling).

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited 1:55PM

    Call EditText's RequestFocus method to set focus, then use SetSelection method to set the cursor position. You can set add a property to RecyclerView's Model class to save the position value.

    EditText editText = FindViewById<EditText>(Resource.Id.edit);
    
    editText.RequestFocus();
    editText.SetSelection(2);
    
Sign In or Register to comment.