Kivy无限卷轴

时间:2016-07-21 19:02:44

标签: android python kivy infinite-scroll

我想为我的应用创建无限滚动。这是我的代码:

from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import AsyncImage


IMAGES_URLS = ['https://upload.wikimedia.org/wikipedia/commons/c/c3/Jordan_by_Lipofsky_16577.jpg' for _ in range(5)]


def upload_images(widget):
    layout = widget.children[0]
    layout_childrens = len(layout.children)
    for url in IMAGES_URLS:
        img = AsyncImage(source=url, size_hint_y=None, height=240)
        layout.add_widget(img)
    widget.scroll_y = 100 - (100 * layout_childrens / (layout_childrens + len(IMAGES_URLS)))


class InfinityScrollView(ScrollView):
    def on_scroll_move(self, touch):
        if self.scroll_y < 0:
            upload_images(self)
        return super(InfinityScrollView, self).on_scroll_move(touch)


class InfiniteScrollApp(App):
    def build(self):
        layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        layout.bind(minimum_height=layout.setter('height'))
        for url in IMAGES_URLS:
            img = AsyncImage(source=url, size_hint_y=None,
                             height=240)
            layout.add_widget(img)
        root = InfinityScrollView(size_hint=(None, None), size=(400, 400),
                                  pos_hint={'center_x': .5, 'center_y': .5})
        root.add_widget(layout)
        return root


if __name__ == '__main__':
    InfiniteScrollApp().run()

我覆盖了on_scroll_move方法,当滚动到底部时,我调用了upload_images方法来添加新图像。

它的工作正常,但我遇到了图像加载后滚动位置保持在底部的问题,但我不会将其移动到第一个加载的图像。

我尝试将正确的值设置为scroll_y,但它不起作用,也许我也必须调用某些方法或更改其他变量。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,我需要覆盖2个变量(scroll_yeffect_y)。这是我在github找到解决方案的问题。这是我的固定代码。

def upload_images(self):
    layout = self.children[0]
    layout_childrens = len(layout.children)
    for url in IMAGES_URLS:
        img = AsyncImage(source=url, size_hint_y=None, height=240)
        layout.add_widget(img)
    bar_position = layout_childrens / (layout_childrens + len(IMAGES_URLS))
    self.scroll_y = 100 - 100 * bar_position
    self.effect_y.value = self.effect_y.min - self.effect_y.min * bar_position