我怎样才能访问recyclerview的点击按钮?
Posted
技术标签:
【中文标题】我怎样才能访问recyclerview的点击按钮?【英文标题】:How can i access the clicked button of a recycle view? 【发布时间】:2022-01-10 15:41:39 【问题描述】:这里是初学者。
我不完全确定下面代码中的所有内容是否正确,但它似乎可以使 recycleview 创建的按钮的大小适应每个按钮的文本。
问题: 如何在 on_release_m 方法中访问(暂时打印)单击按钮的 id?
感谢您的宝贵时间!
from kivy.config import Config
Config.set('graphics', 'width', '270')
Config.set('graphics', 'height', '550')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.lang import Builder
# I included this in case you have to use it for the answer instead of the python code:
Builder.load_string("""
<MyRecycleBoxLayout>:
# orientation: 'vertical'
# default_size: None, None
# default_size_hint: 1, None
# size_hint_y: None
# height: self.minimum_height
<MyButton>:
# font_size: 30
# text_size: self.width, None
# size_hint_y: None
# height: self.texture_size[1]
""")
class MyRecycleBoxLayout(RecycleBoxLayout):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.orientation= 'vertical'
self.default_size= (None, None)
self.default_size_hint=( 1, None)
self.size_hint_y= None
self.bind(minimum_height=self.setter("height"))
class MyButton(Button):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.font_size=30
self.bind(width=lambda s, w: s.setter("text_size")(s, (w, None)))
self.size_hint_y = None
self.bind(texture_size=self.setter("size"))
class RV(RecycleView):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.myRecycleBoxLayout=MyRecycleBoxLayout()
self.data.clear()
for i in range(150):
self.data.append(f"text":f"i "*50,"id": f"btn_i","on_release":self.on_release_m)
self.add_widget(self.myRecycleBoxLayout)
def on_release_m (self,*args):
#Here print the clicked button id and not the first's:
print(self.data[0]["id"])
pass
class RecApp(App):
def build(self):
self.rv=RV()
self.rv.viewclass=MyButton
return self.rv
RecApp().run()
【问题讨论】:
【参考方案1】:您可以使用partial
将其他信息传递给您的on_release_m()
方法:
for i in range(150):
self.data.append(f"text": f"i "*50, "id": f"btn_i", "on_release": partial(self.on_release_m, i))
然后,在on_release_m()
方法中:
def on_release_m(self, i):
#Here print the clicked button id and not the first's:
print(self.data[i]["id"])
【讨论】:
以上是关于我怎样才能访问recyclerview的点击按钮?的主要内容,如果未能解决你的问题,请参考以下文章
Objective C 我们怎样才能改变按钮的背景图像,当它被点击然后恢复正常?