简体   繁体   中英

Pressing back button on Android to close/hide the keyboard is clearing my input field Unity

I have two methods that fire the Unity Event for that input field, try to save the input field value into a variable and then give that value back to Input Field when back button is pressed, but it doesn't work on Android. It works just fine with Unity Editor

public string passwordHolder = "";

public void OnEditting()

{
  if (Application.platform == RuntimePlatform.Android) 
   {
     if (!Input.GetKeyDown(KeyCode.Escape))
      {
         passwordHolder = passwordText.text;
      }
  }

}

public void OnEndEdit()

{

 if (Application.platform == RuntimePlatform.Android) 
       {
            if (Input.GetKeyDown(KeyCode.Escape))
           {              
                  passwordText.text = passwordHolder;               
           }
      }

}

What am I doing wrong?

The "Input" does not work as normal when the keyboard is open. So you can not do the check you do with the "ESC" / back button.

What I have done is creating a method to listen to an event of the keyboard status changing. If it is going to hide (Canceled), I keep the previous text in the field.

I add the script to the object with the InputField component and this is the code that I have put in "Start":

    inputField = gameObject.GetComponent<TMP_InputField>();
    inputField.onEndEdit.AddListener(EndEdit);
    inputField.onValueChanged.AddListener(Editing);
    inputField.onTouchScreenKeyboardStatusChanged.AddListener(ReportChangeStatus);

And this is the code of the methods:

private void ReportChangeStatus(TouchScreenKeyboard.Status newStatus)
{
    if (newStatus == TouchScreenKeyboard.Status.Canceled)
        keepOldTextInField = true;
}

private void Editing(string currentText)
{
    oldEditText = editText;
    editText = currentText;
}

private void EndEdit(string currentText)
{
    if (keepOldTextInField && !string.IsNullOrEmpty(oldEditText))
    {
        //IMPORTANT ORDER
        editText = oldEditText;
        inputField.text = oldEditText;

        keepOldTextInField = false;
    }
}

It works for me and I hope it does for you aswell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM