我的应用程序正在将最新数据从 firebase 返回到 ListView 的底部。但我希望它在顶部!我已经考虑过了,我认为只有两种可能的方法来做到这一点。
1. 反转列表视图。
我认为这种方式应该是这样做的,但我无法弄清楚。我在网上搜索了很多,但没有适合我的情况的解决方案
这是我的适配器代码
public void onStart() {
super.onStart();
// Setup our view and list adapter. Ensure it scrolls to the bottom as data changes
final ListView listView = getListView();
// Tell our list adapter that we only want 50 messages at a time
mChatListAdapter = new ChatListAdapter(mFirebaseRef.limit(50), this, R.layout.chat_message, mUsername);
listView.setAdapter(mChatListAdapter);
}
这是扩展特殊列表适配器类ChatListAdapter
的自定义列表类的构造函数的代码:ChatListAdapter
FirebaseListAdapter
public ChatListAdapter(Query ref, Activity activity, int layout, String mUsername) {
super(ref, Chat.class, layout, activity);
this.mUsername = mUsername;
}
[编辑]这是FirebaseListAdapter
扩展BaseAdapter
类的一些代码
public FirebaseListAdapter(Query mRef, Class<T> mModelClass, int mLayout, Activity activity) {
this.mRef = mRef;
this.mModelClass = mModelClass;
this.mLayout = mLayout;
mInflater = activity.getLayoutInflater();
mModels = new ArrayList<T>();
mModelKeys = new HashMap<String, T>();
// Look for all child events. We will then map them to our own internal ArrayList, which backs ListView
mListener = this.mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
T model = dataSnapshot.getValue(FirebaseListAdapter.this.mModelClass);
mModelKeys.put(dataSnapshot.getKey(), model);
// Insert into the correct location, based on previousChildName
if (previousChildName == null) {
mModels.add(0, model);
} else {
T previousModel = mModelKeys.get(previousChildName);
int previousIndex = mModels.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(model);
} else {
mModels.add(nextIndex, model);
}
}
}
2. 降序查询数据。
第二种方式对我来说是不可能的,因为当我在 Firebase API 文档和网络上搜索时,我无论如何都找不到以降序方式订购回溯数据。
我在 firebase 上的数据如下所示:
glaring-fire-9714
chat
-Jdo7-l9_KBUjXF-U4_c
author: Ahmed
message: Hello World
-Jdo71zU5qsL5rcvBzRl
author: Osama
message: Hi!
谢谢你。