Skip to main content
 首页 » 编程设计

android之自动滚动以重新定位键盘上方的文本输入

2025年05月04日37grandyang

在给定的示例中,如果用户按下回车键或每行达到一定数量的字符,TextInput 将添加一个新行。添加一定数量的新行后,TextInput 将位于 Button 后面,使新行不可见。我希望 ScrollView 自动滚动,以便 TextInput 的最后一行始终位于 Button 之上。

from kivy.app import App 
from kivy.uix.floatlayout import FloatLayout 
from kivy.uix.scrollview import ScrollView 
from kivy.lang import Builder 
from kivy.uix.textinput import TextInput 
 
Builder.load_string(""" 
<MainLayout>: 
    ScrollView: 
        id: sv 
        FloatLayout: 
            size_hint_y: None 
            height: root.height  + tti1.height - tti1.line_height * 3/2 
            TabTextInput: 
                id: tti1 
                font_size: 25 
                size_hint_y: None 
                height: self.line_height*3/2 
                y: root.height - self.line_height * 3/2 
    Button: 
        id: button_id 
        size_hint_y: .5 
        text: 'Keyboard' 
        font_size: 120 
        color: 0,0,0,1 
""") 
 
class TabTextInput(TextInput): 
 
    def __init__(self, *args, **kwargs): 
        super(TabTextInput, self).__init__(*args, **kwargs) 
 
    def keyboard_on_key_down(self, window, keycode, text, modifiers): 
        key, key_str = keycode 
        if key is not 8: 
            if key is 13 or self.cursor_col == 20: 
                self.insert_text('\n') 
                self.add_line() 
                return False 
        else: 
            if self.cursor_col==0 and self.cursor_row>0: 
                self.remove_line() 
        return super(TabTextInput, self).keyboard_on_key_down(window, keycode, text, modifiers) 
 
    def add_line(self): 
        self.height += self.line_height 
 
    def remove_line(self): 
        self.height -= self.line_height 
 
class MainLayout(FloatLayout): 
    pass 
 
class TestApp(App): 
    def build(self): 
        return MainLayout() 
 
 
if __name__ == '__main__': 
    TestApp().run() 

请您参考如下方法:

尝试命名您的 ScrollView,以便您可以引用它。例如,如果您将其称为“ ScrollView ”,则代码应如下所示:

def add_line(self): 
    self.height += self.line_height 
    scrollview.scroll_y=0 

但是您会发现这并不是 100% 正常工作,ScrollView 的 scroll_y 属性为您提供了对滚动的唯一控制。这就是文档所说的:

“Y 滚动值,介于 0 和 1 之间。如果为 0,则内容的底部将触及 ScrollView 的底部。如果为 1,则内容的顶部将触及顶部。”