SearchBar with TabLayout and Viewpager. SearchBar (EditText) doesn't filter through users, nor events

北慕城南 提交于 2020-06-29 03:37:06

问题


My SearchFragment is the host Fragment for two other Fragments: SearchUsersFragment and SearchEventsFragment. The way I have it organized is the TabLayout and Viewpager are in the SearchFragment, and the RecyclerView, Adapters, and ArrayList are in the two child Fragments.

What I would like to do is implement a SearchBar (EditText), which I have already done in the SearchFragment and use that SearchBar to filter through the users (in SearchUsersFragment) and events (in SearchEventsFragment).

The problem: is I have written two methods in each child Fragment searchusers(); and readUsers();. The method searchUsers(); I made public so that I can add it to the SearchFragment in onTextChangedListener, but still the users whose names begin with the letters that I type into the SearchBar aren't coming up.

Can someone please tell me how to fix this? I have been working on this for 3 days and can't get the users or events to come up that start with the letters someone types in the SearchBar.

SearchFragment

public class SearchFragment extends Fragment {

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

        final TabLayout tabLayout = v.findViewById(R.id.tab_layout);
        final ViewPager viewPager = v.findViewById(R.id.viewpager);

        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_people_black));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_event_available_black));

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        viewPagerAdapter.addFragment(new SearchUsersFragment(), "");
        viewPagerAdapter.addFragment(new SearchEventsFragment(), "");

        viewPager.setAdapter(viewPagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));

        EditText searchBar = v.findViewById(R.id.search_bar);
        searchBar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                FragmentManager fragmentManager = getChildFragmentManager();
                SearchUsersFragment searchUsersFragment = (SearchUsersFragment) fragmentManager.findFragmentById(R.id.fragment_search_users);
                if (searchUsersFragment != null) {
                    searchUsersFragment.searchUsers(s.toString().toLowerCase());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        return v;
    }

    static class ViewPagerAdapter extends FragmentPagerAdapter {

        private ArrayList<Fragment> mFragments;
        private ArrayList<String> mTitles;

        ViewPagerAdapter(@NonNull FragmentManager fm) {
            super(fm);
            this.mFragments = new ArrayList<>();
            this.mTitles = new ArrayList<>();
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mTitles.add(title);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
    }
}

SearchUsersFragment

public class SearchUsersFragment extends Fragment {

    RecyclerView mRecyclerView;
    UserAdapter mUserAdapter;
    List<User> mUserList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_users, container, false);

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mUserList = new ArrayList<>();
        mUserAdapter = new UserAdapter(getContext(), mUserList, true);
        mRecyclerView.setAdapter(mUserAdapter);

        readUsers();

        return view;
    }

    public void searchUsers(String s) {
        Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username").startAt(s).endAt(s + "\uf8ff");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mUserList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    if (user != null) {
                        mUserList.add(user);
                    }
                }

                mUserAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    private void readUsers() {
        final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mUserList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    if (firebaseUser != null && user != null && !user.getId().equals(firebaseUser.getUid())) {
                        mUserList.add(user);
                    }
                }

                mUserAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

SearchEventsFragment

public class SearchEventsFragment extends Fragment {

    RecyclerView mRecyclerView;
    SearchEventsAdapter mSearchEventsAdapter;
    List<Post> mPostList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_events, container, false);

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mPostList = new ArrayList<>();
        mSearchEventsAdapter = new SearchEventsAdapter(getContext(), mPostList);
        mRecyclerView.setAdapter(mSearchEventsAdapter);

        readEvents();

        return view;
    }

    private void readEvents() {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mPostList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Post post = snapshot.getValue(Post.class);
                    if (post != null) {
                        mPostList.add(post);
                    }
                }

                mSearchEventsAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

回答1:


I have used a searchView here for filtering 3 fragments together

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            mAdapter.getFilter().filter(newText);
            fAdapter.getFilter().filter(newText);
            rAdapter.getFilter().filter(newText);
            return false;
        }
    });

And then in my adapters I have done implements Filterable and

@Override
public Filter getFilter() {
    return myFilter;
}

private Filter myFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        ArrayList<String> filterList = new ArrayList<>();

        if (constraint == null || constraint.length() == 0) {
            filterList.addAll(MainActivity.Db.getWholeData());
        } else {
            String toFilter = constraint.toString().toLowerCase().trim();

            for (String item : MainActivity.Db.getWholeData()) {
                if (item.toLowerCase().contains(toFilter)) {
                    filterList.add(item);
                }
            }
        }

        clickPurposeFav = filterList;
        FilterResults filterResults = new FilterResults();
        filterResults.values = filterList;

        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {          

        MainActivity.arrList.clear();
        MainActivity.arrList.addAll((List) results.values);

     }
};


来源:https://stackoverflow.com/questions/62236037/searchbar-with-tablayout-and-viewpager-searchbar-edittext-doesnt-filter-thro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!