GameTextInput   Android Game Development Kit의 일부.

GameTextInput 라이브러리를 사용하면 텍스트 입력을 위해 소프트 키보드를 사용하는 전체 화면 Android 앱 작성이 더 간단해집니다.

GameTextInput은 소프트 키보드를 표시하거나 숨기고, 현재 편집된 텍스트를 설정하거나 가져오고, 텍스트가 변경될 때 알림을 받는 간단한 API를 제공합니다. 이 기능은 본격적인 텍스트 편집기 앱을 위한 것은 아니지만 여전히 게임의 일반적인 사용 사례에 대한 선택 및 구성 영역 지원을 제공합니다. 또한 이 라이브러리는 맞춤법 검사, 완성, 멀티 키 문자와 같은 고급 입력 방식 편집기(IME) 기능을 지원합니다.

내부적으로 GameTextInput는 입력 텍스트를 관련 상태와 함께 내부 버퍼 GameTextInput::currentState_에 누적하고 변경사항이 있으면 앱에 알립니다. 그러면 앱이 등록된 콜백 함수에서 텍스트 처리를 실행합니다.

가용성

GameTextInput는 다음과 같은 방법으로 사용할 수 있습니다.

  • GameActivity와 함께: GameActivity는 GameTextInput을 통합합니다. GameActivity를 사용하는 애플리케이션은 통합된 GameTextInput만 사용할 수 있습니다. 사용 안내는 GameActivity 페이지 에 자세히 설명되어 있습니다. GameActivity 및 GameTextInput 통합 샘플은 games-samples 저장소를 참고하세요. 이 사용 모델은 이 가이드의 범위에 속하지 않습니다.

  • 독립형 라이브러리로: 가이드의 나머지 부분에서는 사용 단계를 설명합니다.

위의 두 가지 방법은 상호 배타적입니다.

공식 GameTextInput 출시는 [Google Maven][google-maven]{:.external}의 Jetpack 게임 라이브러리 출시에서 사용할 수 있습니다.

빌드 설정

GameTextInputAndroid 보관 파일 (AAR)로 배포됩니다. 이 AAR에는 GameTextInput의 네이티브 기능을 구현하는 Java 클래스와 C 소스 코드가 포함되어 있습니다. 네이티브 라이브러리와 소스 코드를 CMake 프로젝트 또는 NDK 빌드에 노출하는 Prefab을 통해 빌드 프로세스의 일부로 소스 파일을 포함해야 합니다.

  1. Jetpack Android 게임 페이지의 안내에 따라 GameTextInput 라이브러리 종속 항목을 게임의 build.gradle 파일에 추가합니다. 애플리케이션에서 GameActivity를 사용하는 경우 독립형 GameTextInput 라이브러리를 사용할 수 없습니다.

  2. gradle.properties에 다음 줄이 포함되어 있는지 확인합니다.

    # Tell Android Studio we are using AndroidX.
    android.useAndroidX=true
    # Use Prefab 1.1.2 or higher, which contains a fix for "header only" libs.
    android.prefabVersion=1.1.2
    # Required only if you're using Android Studio 4.0 (4.1 is recommended).
    # android.enablePrefab=true
    
  3. game-text-input 패키지를 가져와서 프로젝트의 CMakeLists.txt 파일에서 대상에 추가합니다.

    find_package(game-text-input REQUIRED CONFIG)
    ...
    target_link_libraries(... game-text-input::game-text-input)
    
  4. 게임의 .cpp 파일 중 하나에서 다음 줄을 추가하여 GameTextInput 구현을 포함합니다.

    #include <game-text-input/gametextinput.cpp>
    
  5. GameTextInput C API를 사용하는 소스 파일에 다음 헤더 파일을 포함합니다.

    #include <game-text-input/gametextinput.h>
    
  6. 앱을 컴파일하고 실행합니다. CMake 오류가 있으면 AAR 및 build.gradle 파일이 올바르게 설정되었는지 확인합니다. #include 파일을 찾을 수 없는 경우 CMakeLists.txt 구성 파일을 확인합니다.

빌드 통합

  1. 이미 JVM에 연결된 C 스레드 또는 앱 기본 스레드에서 JNIEnv 포인터로 GameTextInput_init를 호출합니다.

    static GameTextInput* gameTextInput = nullptr;
    
    extern "C"
    JNIEXPORT void JNICALL
    Java_com_gametextinput_testbed_MainActivity_onCreated(JNIEnv* env,
      jobject this) {
    {
        if(!gameTextInput)
          gameTextInput = GameTextInput_init(env);
        ...
    }
    
  2. InputConnection 액세스 권한이 있는 InputEnabledTextView 자바 클래스를 만듭니다.

    public class InputEnabledTextView extends View implements Listener {
      public InputConnection mInputConnection;
      public InputEnabledTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      public InputEnabledTextView(Context context) {
        super(context);
      }
      public void createInputConnection(int inputType) {
        EditorInfo editorInfo = new EditorInfo();
        editorInfo.inputType = inputType;
        editorInfo.actionId = IME_ACTION_NONE;
        editorInfo.imeOptions = IME_FLAG_NO_FULLSCREEN;
        mInputConnection = new InputConnection(this.getContext(), this,
                new Settings(editorInfo, true)
        ).setListener(this);
      }
    
      @Override
      public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        if (outAttrs != null) {
            GameTextInput.copyEditorInfo(mInputConnection.getEditorInfo(), outAttrs);
        }
        return mInputConnection;
      }
    
      // Called when the IME input changes.
      @Override
      public void stateChanged(State newState, boolean dismissed) {
        onTextInputEventNative(newState);
      }
      @Override
      public void onImeInsetsChanged(Insets insets) {
        // handle Inset changes here
      }
    
      private native void onTextInputEventNative(State softKeyboardEvent);
    }
    
  3. 생성된 InputEnabledTextView를 UI 레이아웃에 추가합니다. 예를 들어 activity_main.xml의 다음 코드는 화면 하단에 배치할 수 있습니다.

    <com.android.example.gametextinputjava.InputEnabledTextView
        android:id="@+id/input_enabled_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
    
  4. 이 새 InputEnabledTextView 클래스를 Java 활동에 가져옵니다. 뷰 결합을 사용하면 비교적 간단합니다.

    public class MainActivity extends AppCompatActivity {
      ...
      private ActivityMainBinding binding;
      private InputEnabledTextView inputEnabledTextView;
    
      private native void setInputConnectionNative(InputConnection c);
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        ...
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        inputEnabledTextView = binding.inputEnabledTextView;
        inputEnabledTextView.createInputConnection(InputType.TYPE_CLASS_TEXT);
        setInputConnectionNative(inputEnabledTextView.mInputConnection);
      }
    
  5. C 라이브러리에서 inputConnectionGameTextInput_setInputConnection에 전달합니다. GameTextInput_setEventCallback에 콜백을 전달하여 C 상태 구조 GameTextInputState의 이벤트에 대한 알림을 받습니다.

    extern "C"JNIEXPORT void JNICALL
    Java_com_gametextinput_testbed_MainActivity_setInputConnectionNative(
      JNIEnv *env, jobject this, jobject inputConnection) {
      GameTextInput_setInputConnection(gameTextInput, inputConnection);
      GameTextInput_setEventCallback(gameTextInput,[](void *ctx, const GameTexgtInputState *state) {
        if (!env || !state) return;
        // process the newly arrived text input from user.
        __android_log_print(ANDROID_LOG_INFO, "TheGreateGameTextInput", state->text_UTF8);
      }, env);
    }
    
  6. C 라이브러리에서 GameTextInput_processEvent를 호출합니다. 이 함수는 이전 단계에서 등록된 콜백을 내부적으로 호출하여 앱이 상태가 변경될 때 이벤트를 처리하도록 합니다.

    extern "C"
    JNIEXPORT void JNICALL
    Java_com_gametextinput_testbed_InputEnabledTextView_onTextInputEventNative(
      JNIEnv* env, jobject this, jobject soft_keyboard_event) {
      GameTextInput_processEvent(gameTextInput, soft_keyboard_event);
    }
    

유틸리티 함수

GameTextInput 라이브러리에는 자바 상태 객체와 C 상태 구조 간에 변환할 수 있는 유틸리티 함수가 포함되어 있습니다. GameTextInput_showImeGameTextInput_hideIme 함수를 통해 IME를 표시하고 숨기기 위한 기능에 액세스합니다.

참조

개발자는 GameTextInput로 앱을 만들 때 다음이 유용할 수 있습니다.

의견

GameTextInput 관련 문제나 질문이 있는 경우 Google Issue Tracker에서 버그를 작성하세요.