Skip to content

Instantly share code, notes, and snippets.

@Cheaterman
Last active November 6, 2021 14:09
Show Gist options
  • Save Cheaterman/7913f70f3721b2f85567cc4a0f50bf3b to your computer and use it in GitHub Desktop.
Save Cheaterman/7913f70f3721b2f85567cc4a0f50bf3b to your computer and use it in GitHub Desktop.
kulo.py
import functools
from dataclasses import dataclass
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import (
BooleanProperty,
ColorProperty,
ListProperty,
StringProperty,
)
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
KV = '''
<PostLine>
text: 'Title: {}'.format(self.title)
background_color: (1, 1, 0, 1) if not self.liked else (1, 0, 0, 1)
size_hint_y: None
height: dp(45)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
<PostsList>:
RecycleView:
data: root._data
viewclass: 'PostLine'
RecycleBoxLayout:
orientation: 'vertical'
spacing: dp(10)
size_hint_y: None
height: self.minimum_size[1]
default_size_hint: 1, None
default_size: None, None
PostsList:
posts: app.posts
on_post_liked: app.on_post_liked(args[1], args[2])
'''
@dataclass
class Post:
id: int
title: str
liked: bool
class PostLine(ButtonBehavior, Label):
__events__ = ('on_post_liked',)
title = StringProperty()
liked = BooleanProperty(False)
background_color = ColorProperty()
def on_press(self):
self.dispatch('on_post_liked', not self.liked)
def on_post_liked(self, liked):
pass
class PostsList(BoxLayout):
__events__ = ('on_post_liked',)
posts = ListProperty()
_data = ListProperty()
def on_posts(self, *args):
self._update_data()
def _update_data(self):
self._data = [
dict(
title=post.title,
liked=post.liked,
on_post_liked=functools.partial(
self.dispatch,
'on_post_liked',
post.id,
),
)
for post in self.posts
]
def on_post_liked(self, post_id, liked):
self._update_data()
class MainApp(App):
posts = ListProperty()
def build(self):
self.posts = [
Post(
id=i,
title='Hello ' + str(i),
liked=(i % 6 == 0),
)
for i in range(1, 21)
]
return Builder.load_string(KV)
def on_post_liked(self, post_id, liked):
for post in self.posts:
if post.id == post_id:
post.liked = liked
break
MainApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment