按标签分类recyclerview项目

时间:2018-12-26 03:52:05

标签: java android firebase firebase-realtime-database

我想根据项目的日期将项目分组为选项卡项目。例如,“星期一”选项卡项仅包含星期一的项目,而星期三的项仅显示在星期三选项卡中。我怎样才能做到这一点?我只想使用1个片段来使其动态。

部分Recycler查看每天的物品

enter image description here

数据库中的项目

Items in database

这是我的代码,用于按天检索时间表。

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference databaseReference =
            firebaseDatabase.getReference(FACULTY)
                    .child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
    databaseReference.keepSynced(true);
    Query query = databaseReference.child(CONSULTATION_SCHEDULES);
    query.keepSynced(true);

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                List<Schedule> schedules = new ArrayList<>();
//              list.clear();

                List<String> days = new ArrayList<>();
                Iterable<DataSnapshot> snapshots = dataSnapshot.getChildren();
                for (DataSnapshot snapshot : snapshots) {
                    Log.d("key1", snapshot.getKey());

                    days.add(snapshot.getKey());
                }

                for (String day : days) {
                    Query scheduleSortReference = ((DatabaseReference) query).child(day); //.orderByChild("day").equalTo(snapshot.getKey())
                    scheduleSortReference.keepSynced(true);
                    scheduleSortReference.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            Iterable<DataSnapshot> dataSnapshots = dataSnapshot.getChildren();
                            for (DataSnapshot snapshot1 : dataSnapshots) {
                                Schedule schedule = Objects.requireNonNull(snapshot1.getValue(Schedule.class)).withId(Objects.requireNonNull(snapshot1.getKey()));
                                Date schedStart = new Date(Long.parseLong(schedule.getTimeStart())); //*1000
                                Date schedEnd = new Date(Long.parseLong(schedule.getTimeEnd())); //*1000

                                DateTime containedStartTime = new DateTime(schedStart);
                                DateTime containedEndTime = new DateTime(schedEnd);

                                Interval interval = new Interval(containedStartTime, containedEndTime);
                                List<Interval> intervals = new ArrayList<>();
                                intervals.add(interval);
                                Collections.sort(intervals, new IntervalStartComparator());
                                Log.d("intervals sorted list?", String.valueOf(intervals) + "\n");

                                schedules.add(schedule);
                            }

                            LinkedHashMap<String, Set<Schedule>> groupedHashMap = groupScheduleDataIntoHashMap(schedules);
                            List<ListItem> consolidatedList = new ArrayList<>();

                            for (String date : groupedHashMap.keySet()) {
                                Log.d("dates", date);
                                DateItem dateItem = new DateItem();
                                dateItem.setDate(date);
                                dateItem.setDay(dayFormat.format(new Date(Long.parseLong(date))));
                                consolidatedList.add(dateItem);
                                for (Schedule schedule : Objects.requireNonNull(groupedHashMap.get(date))) {
                                    GeneralItem generalItem = new GeneralItem();
                                    generalItem.setSchedule(schedule);
                                    consolidatedList.add(generalItem);
                                }
                            }

                            listener.onFindingScheduleSuccess(consolidatedList);
//                          listener.onFindingScheduleSuccess(schedules);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {
                            listener.onFindingScheduleFailure(databaseError.getMessage());
                        }
                    });
                }

            } else {
                listener.onFindingScheduleFailure("You haven't created a schedule yet. Click the image above to start.\n\nYou may also ask your Department Secretary to arrange your Consultation Schedules.");
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            listener.onFindingScheduleFailure(databaseError.getMessage());
        }
    });

这是我添加页面的代码。

@Override
public void getPages(ConsultationDaysListener daysListener) {
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference dayReference = firebaseDatabase.getReference(FACULTY).child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid()).child(CONSULTATION_SCHEDULES);
    dayReference.keepSynced(true);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(((FragmentActivity) context).getSupportFragmentManager());
    List<String> dayKeys = new ArrayList<>();

    dayReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    dayKeys.add(snapshot.getKey());
                }
                for (int i = 0, dayKeysSize = dayKeys.size(); i < dayKeysSize; i++) {
                    String day = dayKeys.get(i);
                    viewPagerAdapter.addFragment(new ConsultationScheduleFragment(), day);
                    viewPagerAdapter.notifyDataSetChanged();
                }
                daysListener.onPageSuccess(viewPagerAdapter, dayKeys.size());
            }
            else {
                viewPagerAdapter.addFragment(new ConsultationScheduleFragment(), "Schedules");
                viewPagerAdapter.notifyDataSetChanged();
                daysListener.onPageFailure(viewPagerAdapter, 1);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            viewPagerAdapter.addFragment(new ConsultationScheduleFragment(), "Schedules");
            viewPagerAdapter.notifyDataSetChanged();
            daysListener.onPageFailure(viewPagerAdapter, 1);
        }
    });
}

这是ConsultationScheduleFragment内部的方法,用于根据日期显示时间表。 (显示标题为星期一以及标题下方的项目)

@Override
public void setSchedules(List<ListItem> schedules) {
    emptySchedImage.setVisibility(View.INVISIBLE);
    emptySchedText.setVisibility(View.INVISIBLE);

    ScheduleGroupAdapter adapter = new ScheduleGroupAdapter(getActivity(), schedules);
    adapter.notifyDataSetChanged();

    recyclerView.setVisibility(View.VISIBLE);

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);

    floatingActionButton.show();
}

这是应用上面的代码后发生的情况。相互切换标签会显示相同的数据。

Repeating data through tab items

3 个答案:

答案 0 :(得分:0)

将RecyclerView与多个视图持有者一起使用,可以实现这一目标。 这里是一个链接,可以给您一个不错的主意。 http://www.digitstory.com/recyclerview-multiple-viewholders/

答案 1 :(得分:0)

我认为您可以在片段的RecyclerView调用中使用onResume(),这样整个RecyclerView就会为每个选项卡(如星期一/星期三)初始化。

答案 2 :(得分:0)

我以某种方式设法解决了我的问题:

我从星期一到星期天创建了不同名称的片段

private ConsultationScheduleFragment monday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment tuesday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment wednesday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment thursday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment friday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment saturday = new ConsultationScheduleFragment();
private ConsultationScheduleFragment sunday = new ConsultationScheduleFragment();

在我的getPages方法中,对于根据工作日正确命名的标题,我使用了两组for循环和一个比较器使之类似

enter image description here

字符串比较器

Comparator<String> dateComparator = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        try{
            SimpleDateFormat format = new SimpleDateFormat("EEE", Locale.ENGLISH);
            Date d1 = format.parse(s1);
            Date d2 = format.parse(s2);
            if(d1.equals(d2)){
                return s1.substring(s1.indexOf(" ") + 1).compareTo(s2.substring(s2.indexOf(" ") + 1));
            }else{
                Calendar cal1 = Calendar.getInstance();
                Calendar cal2 = Calendar.getInstance();
                cal1.setTime(d1);
                cal2.setTime(d2);
                return cal1.get(Calendar.DAY_OF_WEEK) - cal2.get(Calendar.DAY_OF_WEEK);
            }
        }catch(ParseException pe){
            throw new RuntimeException(pe);
        }
    }
};

我还使用putString捆绑包在每个工作日准确添加它们

Bundle mondayBundle = new Bundle();
Bundle tuesdayBundle = new Bundle();
Bundle wednesdayBundle = new Bundle();
Bundle thursdayBundle = new Bundle();
Bundle fridayBundle = new Bundle();
Bundle saturdayBundle = new Bundle();
Bundle sundayBundle = new Bundle();

这是处理的地方

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
     dayKeys.add(snapshot.getKey());
}
List<String> days = new ArrayList<>();
for (int i = 0, dayKeysSize = dayKeys.size(); i < dayKeysSize; i++) {
     String day = dayKeys.get(i);
     days.add(day);
     Collections.sort(days, dateComparator);
}
for (String sortedDay : days) {
     if ("Monday".equals(sortedDay)) {
         mondayBundle.putString(SCHEDULE_DAY, "Monday");
         monday.setArguments(mondayBundle);
         viewPagerAdapter.addFragment(monday, "Monday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Tuesday".equals(sortedDay)) {
         tuesdayBundle.putString(SCHEDULE_DAY, "Tuesday");
         tuesday.setArguments(tuesdayBundle);
         viewPagerAdapter.addFragment(tuesday, "Tuesday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Wednesday".equals(sortedDay)) {
         wednesdayBundle.putString(SCHEDULE_DAY, "Wednesday");
         wednesday.setArguments(wednesdayBundle);
         viewPagerAdapter.addFragment(wednesday, "Wednesday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Thursday".equals(sortedDay)) {
         thursdayBundle.putString(SCHEDULE_DAY, "Thursday");
         thursday.setArguments(thursdayBundle);
         viewPagerAdapter.addFragment(thursday, "Thursday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Friday".equals(sortedDay)) {
         fridayBundle.putString(SCHEDULE_DAY, "Friday");
         friday.setArguments(fridayBundle);
         viewPagerAdapter.addFragment(friday, "Friday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Saturday".equals(sortedDay)) {
         saturdayBundle.putString(SCHEDULE_DAY, "Saturday");
         saturday.setArguments(saturdayBundle);
         viewPagerAdapter.addFragment(saturday, "Saturday");
         viewPagerAdapter.notifyDataSetChanged();
     }
     if ("Sunday".equals(sortedDay)) {
         sundayBundle.putString(SCHEDULE_DAY, "Sunday");
         sunday.setArguments(sundayBundle);
         viewPagerAdapter.addFragment(sunday, "Sunday");
         viewPagerAdapter.notifyDataSetChanged();
     }
}

经过上述处理,我在目标片段中调用了参数

@Override
public void onStart() {
    super.onStart();
    presenter.onStart();

    Bundle bundle = this.getArguments();
    String day = Objects.requireNonNull(bundle).getString(SCHEDULE_DAY);
    presenter.requestScheduleAccordingToDay(day);
}

终于成功了! Yaaaay