AutoScroll在键盘上方重新定位textinput

时间:2015-03-07 13:09:19

标签: android python kivy

在给定的示例中,如果用户按Enter键或每行达到一定数量的字符,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()

1 个答案:

答案 0 :(得分:1)

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

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

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

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