如何处理Firebase Adapter RecyclerView空视图?

时间:2017-03-31 14:25:53

标签: android firebase firebase-realtime-database android-recyclerview

所以问题是每当我为回收者视图设置我的空视图时,它总是显示空视图。我尝试了一些建议的解决方案,例如此网址中的一个:FirebaseRecyclerAdapter with empty view,但问题是Firebase侦听器是异步的并且在自己的线程上运行。在设置空视图之前,片段的onCreateView方法已经返回视图,因此未正确设置空视图。有没有其他方法可以实现FirebaseRecyclerAdapter的空视图设置?

以下是代码片段:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.activity_list, container, false);

    initializeFilter();

    Log.d("AttendanceFragment", filter.getTab() + "");

    Firebase.setAndroidContext(getContext());

    //filter(filter);
    handleFilter();

    if(getContext() != null) {
        adapter = new AttendanceAdapter(Attendance.class, R.layout.list_item, AttendanceAdapter.AttendanceViewHolder.class, mDatabase);

        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("DATA_CHANGED", dataSnapshot.hasChildren() + "");

                if(!dataSnapshot.hasChildren()){
                    Log.d("SETTING", setEmpty + "");
                    if(filter.getTab() == 1) {
                        empty = (TextView) v.findViewById(R.id.empty_view);
                        empty.setText("No finished attendance yet");
                    }

                    recView.setEmptyView(v.findViewById(R.id.empty_view));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        Log.d("FIREBASE", recView.getAdapter().getItemCount() + "");
    }

    adapter.setOnItemClickListener(new AttendanceAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(String name) {
            Toast.makeText(getContext(), name, Toast.LENGTH_SHORT).show();
        }
    });

    recView.setAdapter(adapter);

    return v;
}

它基本上检查dataSnapshot是否没有任何子节点,如果它没有任何子节点,它会设置空视图。问题是在onDataChange()之前首先调用setAdapter()。

1 个答案:

答案 0 :(得分:1)

recView.setAdapter(adapter)放在recView.setEmptyView(v.findViewById(R.id.empty_view))之后,以便更好地练习[{1}}或ProgressBar