【问题标题】:Python: how do I can use android.show_keyboard for my android app?Python:如何为我的 android 应用程序使用 android.show 键盘?
【发布时间】:2021-09-20 12:04:02
【问题描述】:

我编写了一个小型 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 中)(但我可以绘制它们),所以我想在代码中显示/隐藏键盘。 但我找不到关于 android.show_keyboard 和 android.hide_keyboard 的文档

我的尝试:

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

有人可以帮助我如何显示/隐藏键盘吗?

【问题讨论】:

    标签: python android pygame keyboard


    【解决方案1】:

    如Python for Android documentation 中所述,android 是一个 Cython 模块,“用于 Android API 与 Kivy 的旧界面交互,但现在大部分被 Pyjnius 取代。”

    因此,我发现的解决方案是基于 Pyjnius,本质上是复制用于在 Android 上隐藏和显示键盘的 Java 代码(我使用 this answer 作为基础,但可能会有更好的东西) ,通过利用基于 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 for Android 文档中的 section related to Automatic Recursive Inspection。

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 2012-08-05
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      相关资源
      最近更新 更多