每次发生事件时如何创建屏幕的新实例

时间:2020-02-20 17:04:28

标签: python kivy

我想每次有人向新人发送消息时都创建一个新的聊天屏幕实例,我创建了按钮的列表视图,并且每次有人向新人发送消息时都添加了一个按钮,但是我正在尝试弄清楚如何将其定向到包含交互的所有消息的唯一聊天页面。任何帮助,将不胜感激。以下是我的代码

class Chat(Screen):

    def on_enter(self, *args):
        app = App.get_running_app()
        self.chatdestination = Label(
            text=firebase.get("/users/" + app.localId, 'first name') + " " + firebase.get('/users/' + app.localId,
                                                                                          'last name'),
            pos_hint={"center_x": 0.5, "center_y": 0.95}, size_hint=[0.8, 0.1], color=(0, 0, 0, 1),
            font_name="fonts/Qanelas-Light.otf")

        self.add_widget(self.chatdestination)


    def __init__(self, **kwargs):
        super(Chat, self).__init__(**kwargs)
        self.localId = None
        self.messagebutton = Button(text="Send", font_size = 20, font_name= "fonts/Qanelas-Heavy.otf", background_color= (0.082, 0.549, 0.984, 1.0), background_normal= '', pos_hint= {"right": 1,"down": 1}, size_hint= [0.2, 0.1])
        self.messagebutton.bind(on_release = self.send_message)
        self.add_widget(self.messagebutton)


        self.messagetextinput = TextInput(width=Window.size[0]*0.8, hint_text= "Write a message", font_name= "fonts/Qanelas-Light.otf", size_hint= [0.8, 0.1], pos_hint= {"left": 1,"down": 1})
        self.add_widget(self.messagetextinput)



        Window.bind(on_key_down=self.on_key_down)

        Clock.schedule_once(self.focus_text_input, 1)

    def on_key_down(self, instance, keyboard, keycode, text, modifiers):
        if keycode == 40:
            self.send_message(None)



    def send_message(self, _):
        app = App.get_running_app()
        message = self.messagetextinput.text
        if len(message) > 0:
            database.child("messages").child(app.localId).update({self.localId: message})
            self.chatbubble = Button(text=self.messagetextinput.text, background_color = [0.082, 0.549, 0.984, 1.0], background_normal = "",
                                      pos_hint= {"center_x": 1}, color = (1, 1, 1, 1), size_hint_y = None)
            self.chatbubble.size = self.chatbubble.texture_size

            self.ids.chatlayout.add_widget(self.chatbubble)
            self.ids.scrollview.scroll_to(self.chatbubble)
            self.messagetextinput.text = ""


            Clock.schedule_once(self.focus_text_input, 0.1)


            messages_list = []
            if app.localId not in messages_list:
                messages_list.append(app.localId)
                for id in messages_list:
                    messages_screen = self.manager.get_screen('messages')
                    messages_screen.messages_list.adapter.data.extend([])

1 个答案:

答案 0 :(得分:0)

您应该查看RecycleViews。 我认为最好的选择可能是拥有一个将您的“聊天”用作视图类的RecycleView。