我正在编写一个 IM 客户端,我需要下载(从文件系统或网络)并在 ListView 的顶部显示新元素(它是消息的历史——旧消息在顶部,新消息在底部)。我为 ListView 实现了自己的适配器,但我无法在列表的开头添加新元素并重绘它。(notifyDataSetChanged() 对我不好,因为 ListView 中的消息索引发生了变化,android 无法正常重绘它)。
其他应用程序如何做类似的事情?
我没有为它创建特殊代码,我只是为我的 ListView 创建新的适配器:
messagesListView.setAdapter(new MessagesListAdapter(this));
并在 MessagesListAdapter 中重新定义 getView() 和 getCount() 方法(现在扩展 ArrayAdapter)。
我的 ListView 的 XML 是
<ListView
android:id="@+id/dialog_messages_list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginTop="@dimen/title_height">
</ListView>
我的一个元素(一条消息)的 XML 是
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/dialogMessageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:background="@drawable/dialog_message_in"
/>
<TextView
android:id="@+id/dialogMessageDatetime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
可能你需要其他代码吗?
编辑:我试过
messagesListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList));
(new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
arrayList.add(0, "qwer");
}
}).start();
但这似乎也不太好。我试图调用((ArrayAdapter<String>)messagesListView.getAdapter()).notifyDataSetChanged();
线程,但它产生了异常。