Python:如何将 android.show_keyboard 用于我的 android 应用程序?

Python: how do I can use android.show_keyboard for my android app?

我写了一个小 pygame 应用程序,可以在设备屏幕上填充随机颜色:

import sys, os
andr = None # is running on android
try:
    import android
    andr = True
except ImportError:
    andr = False
try:
    import pygame
    import sys
    import random
    import time
    from pygame.locals import *
    pygame.init() 
    fps = 1 / 3  # 3 fps
    width, height = 640, 480
    screen = pygame.display.set_mode((width, height), FULLSCREEN if andr else 0) # fullscreen is required on android
    width, height = pygame.display.get_surface().get_size() # on android resolution is auto changing to screen resolution
    while True:
        screen.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.flip()
        time.sleep(fps)
except Exception as e:
    open('error.txt', 'w').write(str(e)) # Save error into file (for android)

但是没有 UI 元素(就像在 kivy 中一样)(但我可以绘制它们),所以我想从代码中 show/hide 键盘。 但是我找不到关于 android.show_keyboard 和 android.hide_keyboard

的文档

我的尝试:

  1. 当我调用 android.show_keyboard() 时,我收到一条错误消息,指出需要 2 个参数
  2. 当我添加随机参数时:android.show_keyboard(True, True),我也收到一条错误消息说 var input_type_ 不是全局的
  3. 当我将第二个参数更改为字符串时:android.show_keyboard(True, 'text'),应用程序崩溃而没有将错误保存到文件。

谁能帮我 show/hide 键盘?

Python for Android documentation 中所述,android 是一个 Cython 模块“用于 Android API 与 Kivy 旧界面的交互,但是现在主要由 Pyjnius."

取代

因此,我找到的解决方案是基于 Pyjnius,主要包括复制 Java 代码,用于在 Android 上隐藏和显示键盘(我使用 作为一个基础,但可能有更好的东西),通过利用基于 Pyjnius autoclass 的语法:

from jnius import autoclass


def show_android_keyboard():
    InputMethodManager = autoclass("android.view.inputmethod.InputMethodManager")
    PythonActivity = autoclass("org.kivy.android.PythonActivity")
    Context = autoclass("android.content.Context")
    activity = PythonActivity.mActivity
    service = activity.getSystemService(Context.INPUT_METHOD_SERVICE)
    service.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)


def hide_android_keyboard():
    PythonActivity = autoclass("org.kivy.android.PythonActivity")
    Context = autoclass("android.content.Context")
    activity = PythonActivity.mActivity
    service = activity.getSystemService(Context.INPUT_METHOD_SERVICE)
    service.hideSoftInputFromWindow(activity.getContentView().getWindowToken(), 0)

如果您想详细了解 Pyjinius 的 autoclass 是如何工作的,请查看 Python 中的 Android 文档的 section related to Automatic Recursive Inspection