我正在开发问答应用程序。我已成功从 firebase 加载问题。但我无法像数据库一样从 Firebase 应用分页。以及如何识别我们已经到达回收站 View 的末尾,以便可以加载接下来的几个问题。
最佳答案
要识别我们已经到达 RecyclerView
的末尾,您可以使用此类 EndlessRecyclerOnScrollListener.java
要加载更多下一个问题,您应该在 Question class
中再定义一个字段,例如 number
public class Question {
private int number; // it must unique and auto increase when you add new question
...
}
然后,当您从 FireBase
加载问题时,您可以这样做
public class MainActivity extends AppCompatActivity {
private static final int TOTAL_ITEM_EACH_LOAD = 10;
private DatabaseReference mDatabase;
final List<Question> questionList = new ArrayList<>();
private int currentPage = 0;
private RecyclerView recyclerView;
private RecyclerViewAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// init and set layout manager for your RecyclerView
...
mAdapter = new RecyclerViewAdapter(questionList);
recyclerView.setAdapter(mAdapter);
recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int current_page) { // when we have reached end of RecyclerView this event fired
loadMoreData();
}
});
loadData(); // load data here for first time launch app
}
private void loadData() {
// example
// at first load : currentPage = 0 -> we startAt(0 * 10 = 0)
// at second load (first loadmore) : currentPage = 1 -> we startAt(1 * 10 = 10)
mDatabase.child("questions")
.limitToFirst(TOTAL_ITEM_EACH_LOAD)
.startAt(currentPage*TOTAL_ITEM_EACH_LOAD)
.orderByChild("number")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChildren()){
Toast.makeText(MainActivity.this, "No more questions", Toast.LENGTH_SHORT).show();
currentPage--;
}
for (DataSnapshot data : dataSnapshot.getChildren()) {
Question question = data.getValue(Question.class);
questionList.add(question);
mAdapter.notifyDataSetChanged();
}
}
@Override public void onCancelled(DatabaseError databaseError) {}});
}
private void loadMoreData(){
currentPage++;
loadData();
}
}
关于android - 使用 firebase 在无尽的回收器 View 中分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289731/