我编写了一个小游戏应用程序,在设备的屏幕上填充随机颜色:
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的文档
我的尝试:
android.show_keyboard()时,我会收到一个错误,说明需要两个areandroid.show_keyboard(True, True)时,还会看到一个错误,即var input_type_不是全局的。android.show_keyboard(True, 'text')时,应用程序就会崩溃,而不会将错误保存到文件中。有人能帮我如何显示/隐藏键盘吗?
发布于 2021-08-30 10:48:05
正如用于Android文档的Python中所指定的,android是一个Cython模块,“用于与Kivy的旧接口进行Android交互,但现在主要被Pyjnius所取代。”
因此,我找到的解决方案是基于Pyjnius的,本质上包括复制用于在Android上隐藏和显示键盘的Java代码(我使用这个答案作为基础,但可能有更好的方法),方法是利用Pyjnius autoclass-based语法:
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文档中的与自动递归检查有关的部分。
https://stackoverflow.com/questions/68328438
复制相似问题