首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:我如何在我的安卓应用程序中使用android.show_keyboard?

Python:我如何在我的安卓应用程序中使用android.show_keyboard?
EN

Stack Overflow用户
提问于 2021-07-10 14:06:06
回答 1查看 559关注 0票数 1

我编写了一个小游戏应用程序,在设备的屏幕上填充随机颜色:

代码语言:javascript
复制
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()时,我会收到一个错误,说明需要两个are
  2. 当我添加随机args:android.show_keyboard(True, True)时,还会看到一个错误,即var input_type_不是全局的。
  3. 当我将第二个arg更改为string:android.show_keyboard(True, 'text')时,应用程序就会崩溃,而不会将错误保存到文件中。

有人能帮我如何显示/隐藏键盘吗?

EN

Stack Overflow用户

回答已采纳

发布于 2021-08-30 10:48:05

正如用于Android文档的Python中所指定的,android是一个Cython模块,“用于与Kivy的旧接口进行Android交互,但现在主要被Pyjnius所取代。”

因此,我找到的解决方案是基于Pyjnius的,本质上包括复制用于在Android上隐藏和显示键盘的Java代码(我使用这个答案作为基础,但可能有更好的方法),方法是利用Pyjnius autoclass-based语法:

代码语言:javascript
复制
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如何工作,请看一下Pyjinius在Python文档中的与自动递归检查有关的部分

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68328438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档