Skip to content

Instantly share code, notes, and snippets.

@tito
Last active June 7, 2022 22:29
Show Gist options
  • Save tito/4201bc10d9752eb2762d31ce8fb699b6 to your computer and use it in GitHub Desktop.
Save tito/4201bc10d9752eb2762d31ce8fb699b6 to your computer and use it in GitHub Desktop.
Kivy RecycleView with dynamic height content

Sometimes, you have RecycleView with unknown height item, and you wish it would work. One idea from tshirtman is to precompute an height approximation and pass it to each item. This approach is to save the latest computed size when the widget is created back into its own data.

Theses are just notes, you have to figure out what to use for your own application.

Data example:

[
  {
    "height": dp(48), # minimum size or default size
    ...
  },
  ...
]

KV example:

<YourWidget>:
    RecycleView:
        viewclass: "ActivityFeedEntry"
        key_size: "height"
        RecycleBoxLayout:
            default_size: None, None
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: 'vertical'

Python:

from kivy.uix.recycleview.views import RecycleDataViewBehavior

class ActivityFeedEntry(RecycleDataViewBehavior, BoxLayout):
    _latest_data = None
    _rv = None
 
    def refresh_view_attrs(self, rv, index, data):
        self._rv = rv
        if self._latest_data is not None:
            self._latest_data["height"] = self.height
        self._latest_data = data
        super(ActivityFeedEntry, self).refresh_view_attrs(rv, index, data)
 
    def on_height(self, instance, value):
        data = self._latest_data
        if data is not None and data["height"] != value:
            data["height"] = value
            self._rv.refresh_from_data()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment