ListView中的setAdapter就像addView一样,而不仅仅是在View上添加文本

时间:2015-02-19 14:50:29

标签: java android listview view add

我的名字是Francesco,我正在尝试创建一个聊天应用程序,只是为了看看我花多少时间去做。 不幸的是,这对我来说似乎是个错误,但也许我错了。

我有3节课:

  1. 分享变量的全局类。
  2. 一个FriendList类。
  3. ChatRoom类。
  4. “buggy”代码片段已进入ChatRoom类。它在FriendList类中运行得非常好,它只使用ListView中的setAdapter方法,但是当它必须使用它时,它不是向ListView添加文本,而是添加2个视图(autoCompleteTextView和一个Button),即2我在ChatRoom类中使用的视图来编写和发送消息......

    ChatRoom的布局与FriendList相同,区别在于ChatRoom中有一个autoCompleteTextView,一个发送消息的Button和两个TextView而不是一个,因为我想把不同的消息放在右边或者留下,取决于谁写了这条消息。

    FriendList代码:

    friendList = (ListView) findViewById(R.id.mainListView);
    
    list = new ArrayList<String>();
    
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(currentActivity, R.layout.friendlist_layout, R.id.textview, list);
    friendList.setAdapter(adapter);
    
    adapter.add("francesco");
    adapter.add("funkyserver");
    
    friendList.setAdapter(adapter);
    

    ChatRoom代码:

    public void onClick(View v) {
            try {
                String messageToSend = messageInput.getText().toString();
                if (messageToSend != "" | messageToSend != null) {
                                chat.sendMessage(messageInput.getText().toString());
                        messageListAdapterR.add(messageToSend);
                        messageListAdapterL.add("");
                        currentActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                    messageListView.setAdapter(messageListAdapterL);
                                    messageListView.setAdapter(messageListAdapterR);
                            }
                        });
                }
    
           ...
    

    P.S。这两个代码都是runOnUiThread。

    提前感谢您的回复:)

1 个答案:

答案 0 :(得分:0)

修改附加到绑定到ListView的适配器的数据时,不要再次调用setAdapter()来更新视图。这就是notifyDataSetChanged()的用途。你的第一个伪代码样本应该看起来像这样:

friendList = (ListView) findViewById(R.id.mainListView);

list = new ArrayList<String>();

ArrayAdapter<String> adapter = new ArrayAdapter<String>(currentActivity,
        R.layout.friendlist_layout, R.id.textview, list);
friendList.setAdapter(adapter);

adapter.add("francesco");
adapter.add("funkyserver");

adapter.notifyDataSetChanged();

实际上,为了更加精确,在直接向适配器添加项目时,甚至不需要notifyDataSetChanged() ...它应该在内部调用该方法。

关于第二个示例,ListView无法显示来自多个适配器的数据。代码调用时:

messageListView.setAdapter(messageListAdapterL);
messageListView.setAdapter(messageListAdapterR);

第二种方法是先调用 覆盖 ,您将看到的所有内容都来自messageListAdapterR。如果您希望视图中显示两个“列表”中的数据,则必须将它们组合到一个适配器中。