如何根据其他类中不断变化的变量加载Kivy RecycleView



我正在尝试创建一个RecycleView,它列出了许多根据所选日期而变化的项目,并且只显示特定用户的项目。我为我的应用程序创建了一个登录函数,当被调用时,它会将current_user设置为数据库中的用户id。我认为我的问题是,当我运行应用程序时,RecycleView是在我加载它所在的屏幕之前使用默认值(0(创建的。有没有办法延迟RecycleView的初始化,以便它接受新的app.get_running_app((.current_user和app.get_running_app.current_day_id值?

我知道这些值正在正确更新,因为当我登录并选择日期并尝试打印值时,它会打印更改后的值,而不是默认值。

它的工作方式是I登录,它设置App.get_running_App((.current_user值并显示主屏幕。然后,当我选择一个日期时,它会设置App.get_running_App((.current_day_id并显示当天的屏幕,也就是显示RecycleView的地方。

下方列出的释放代码

# My RV claass
class SnapshotsRV(MDRecycleView):
def __init__(self, **kwargs):
super(SnapshotsRV, self).__init__(**kwargs)
conn = sqlite3.connect("site.db")
c = conn.cursor()
# with these two variables, I want to get the updated values. Not the values that I set 
initially
user = App.get_running_app().current_user
day = App.get_running_app().current_day_id
c.execute("SELECT * FROM snapshot WHERE user_id=? AND day=?", (user, day,))
snapshots = c.fetchall()
self.data = [{'text': snapshot[2]} for snapshot in snapshots]
conn.commit()
conn.close()

class JournalApp(MDApp):
#Set the initial values
current_user = NumericProperty(0)
current_date = StringProperty("")
current_day_id = NumericProperty(None)
def build(self):
return Builder.load_file('app.kv')

感谢您的帮助。我自学成才,还在学习!

我想我已经想通了,至少部分想通了。这样做的方法似乎是调用on_pre_enter((,它必须在屏幕上而不是在RecycleView上调用。我在DateView(包含rv的类(中创建了一个获取rv数据的函数和一个设置数据的函数,然后在on_pre_enter((中调用这些方法,该方法在选择日期时动态加载数据。

为了在用户返回主页并选择不同的日期时重置它,我创建了一个clear_rv_data((函数,该函数将数据设置为空列表。每次访问页面时都会更新

在我的kv文件中:

<SnapshotsRV>
viewclass: 'MDRaisedButton'
RecycleBoxLayout:
default_size: None, 100
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
<DateView>
snapshots_rv: snapshots_rv
MDBoxLayout:
orientation: "vertical"
id: snapshot_grid
SnapshotsRv:
id: snapshots_rv
MDRaisedButton:
text: "Home"
on_release: app.root.current = "home"; root.clear_rv_data()

和我的python文件

class DateView(MDScreen):
def __init__(self, **kwargs):
super(DateView, self).__init__(**kwargs)
def on_pre_enter(self, *args):
rv_data = self.get_rv_data()

# use the id to update the recycleview data
for snapshot in rv_data:
self.ids.snapshots_rv.data = [{'text': snapshot[2]} for snapshot in rv_data]
def clear_rv_data(self):
#this resets the data when the screen is left, so that when a new day is chosen it can show the updated data
self.snapshots_rv.data = []
self.ids.snapshots_rv.refresh_from_data()
def get_rv_data(self):
conn = sqlite3.connect("site.db")
c = conn.cursor()

day = App.get_running_app().current_day_id
user = App.get_running_app().current_user
c.execute("SELECT * FROM snapshot where user_id == ? AND day_id=?", (user, day,))
snapshots = c.fetchall()
conn.commit()
conn.close()
return snapshots

class JournalApp(MDApp):
current_user = NumericProperty(0)
current_day_id = NumericProperty(0)
def build(self):
return Builder.load_file('app.kv')

最新更新