来自代码的Kivy ListAdapter / Listview scroll_to在触摸后不起作用(包括示例)

时间:2016-06-15 10:46:00

标签: python listview kivy

我试图对播放歌曲的播放器进行编码,跳转到目录ListView中的混洗歌曲,并在歌曲不在视野时将ListView滚动到该歌曲。可悲的是,每次都不起作用。

在下面的示例中,当您按下按钮直到触摸ListView时,ListView将滚动到所需的项目。触摸/滚动ListView后,它将不再滚动到该项目。

知道我的代码有什么问题吗?

from kivy.uix.boxlayout import BoxLayout
from kivy.adapters.dictadapter import ListAdapter
from kivy.uix.button import Button
from kivy.uix.listview import ListView, ListItemButton
from kivy.uix.label import Label

from random import randint

class MainView(BoxLayout):
    items = 400

    def __init__(self, **kwargs):
        super(MainView, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.change_from_code = False
        self.list_adapter = ListAdapter(data=["Item #{0}".format(i) for i in range(self.items)], cls=ListItemButton, sorted_keys=[])
        self.list_adapter.bind(on_selection_change=self.selection_change)
        self.list_view = ListView(adapter=self.list_adapter)
        self.add_widget(self.list_view)
        self.status = Label(size_hint_y=.1)
        self.add_widget(self.status)
        self.add_widget(Button(text="select random item", on_press=self.button_pressed,size_hint_y=.1))

    def button_pressed(self, btn):
        index = randint(0, self.items-1)

        self.change_from_code = True
        if not self.list_adapter.get_view(index).is_selected:           # select another random item
            self.list_adapter.get_view(index).trigger_action(duration=0)

    def selection_change(self, adapter, *args):
        selected_index= adapter.selection[0].index      # <--- problem: scroll_to does not work always
        self.list_view.scroll_to(selected_index)

        if self.change_from_code:
            self.status.text= "selection change from code btn %s" %adapter.selection[0].text
        else:
            self.status.text= "selection changed by click btn %s" %adapter.selection[0].text
        self.change_from_code=False

if __name__ == '__main__':
    from kivy.base import runTouchApp
    runTouchApp(MainView(width=800))

0 个答案:

没有答案