How to detect “done” Button in softkeyboard Unity3d

对着背影说爱祢 提交于 2019-12-07 19:58:35

问题


I use a InputField in my android app to get a string a soft keyboard pops up when i'm entering a string but now i want to call a function when user press "done" button in softkeyboard how can i do that?
Unity3d 4.6.2f1


回答1:


the best way i found is to subclass InputField. You can look into the source for the UnityUI on bitbucket. In that subclass you can access the protected m_keyboard field and check whether done was pressed AND not canceled, that will give you the desired result. Using "submit" of the EventSystem doesn't work properly. Even nicer when you integrate it into the Unity EventSystem.

Something like this: SubmitInputField.cs

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine.Events;
using System;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

public class SubmitInputField : InputField
{
    [Serializable]
    public class KeyboardDoneEvent : UnityEvent{}

    [SerializeField]
    private KeyboardDoneEvent m_keyboardDone = new KeyboardDoneEvent ();

    public KeyboardDoneEvent onKeyboardDone {
        get { return m_keyboardDone; }
        set { m_keyboardDone = value; }
    }

    void Update ()
    {
        if (m_Keyboard != null && m_Keyboard.done && !m_Keyboard.wasCanceled) {
            m_keyboardDone.Invoke ();
        }
    }
}

Editor/SubmitInputFieldEditor.cs

using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;
using UnityEditor.UI;

[CustomEditor (typeof(SubmitInputField), true)]
[CanEditMultipleObjects]
public class SubmitInputFieldEditor : InputFieldEditor
{
    SerializedProperty m_KeyboardDoneProperty;
    SerializedProperty m_TextComponent;

    protected override void OnEnable ()
    {
        base.OnEnable ();
        m_KeyboardDoneProperty = serializedObject.FindProperty ("m_keyboardDone");
        m_TextComponent = serializedObject.FindProperty ("m_TextComponent");
    }


    public override void OnInspectorGUI ()
    {
        base.OnInspectorGUI ();
        EditorGUI.BeginDisabledGroup (m_TextComponent == null || m_TextComponent.objectReferenceValue == null);

        EditorGUILayout.Space ();

        serializedObject.Update ();
        EditorGUILayout.PropertyField (m_KeyboardDoneProperty);
        serializedObject.ApplyModifiedProperties ();

        EditorGUI.EndDisabledGroup ();
        serializedObject.ApplyModifiedProperties ();
    }
}



回答2:


You should be able to achieve the same by using this:

function Update () {
        Event e = Event.currrent;
        if (e.type == EventType.keyDown && e.keyCode == KeyCode.Return)
            //Put in what you want here
    }


来源:https://stackoverflow.com/questions/29670276/how-to-detect-done-button-in-softkeyboard-unity3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!