如何实现SearchView来过滤RecyclerView元素

时间:2018-12-23 07:31:09

标签: android android-adapter android-search

我正在尝试从支持库中实现SearchView。我希望用户能够在RecyclerView中搜索/过滤帖子列表。

到目前为止,我已经按照一些教程进行了操作,并将SearchView添加到了ActionBar中,但还不确定从何处去。我看到了一些示例,但是当用户开始在SearchView中键入内容时,它们都没有显示结果。

PostAdapter.java:

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> implements Filterable {

    private Context context;
    private List<Item> items;
    private List<Item> mFilteredList;

    public PostAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.post_item, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(PostViewHolder holder, int position) {
        final Item item = items.get(position);
        holder.postTitle.setText(item.getTitle());
        Document document = Jsoup.parse(item.getContent());
        Elements elements = document.select("img");
        Glide.with(context).load(elements.get(0).attr("src")).into(holder.postImage);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DetailActivity.class);
                intent.putExtra("pid", item.getId());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }


    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    mFilteredList = items;
                } else {

                    ArrayList<Item> filteredList = new ArrayList<>();

                    for (Item item : items) {

                        if (item.getTitle().toLowerCase().contains(charString) || item.getContent().toLowerCase().contains(charString)) {

                            filteredList.add(item);
                        }
                    }

                    mFilteredList = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = mFilteredList;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                mFilteredList = (List<Item>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }



    public class PostViewHolder extends RecyclerView.ViewHolder {
        ImageView postImage;
        TextView postTitle;


        public PostViewHolder(View itemView) {
            super(itemView);
            postImage = (ImageView) itemView.findViewById(R.id.postImage);
            postTitle = (TextView) itemView.findViewById(R.id.postTitle);

        }

    }


}

我的MainActivity.java:

public class MainActivity extends AppCompatActivity {

        DrawerLayout drawerLayout;
        Toolbar toolbar;
        ActionBarDrawerToggle actionBarDrawerToggle;
        NavigationView navigationView;
        RecyclerView recyclerView;
        LinearLayoutManager manager;
        PostAdapter adapter;
        List<Item> items = new ArrayList<>();
        Boolean isScrolling = false;
        int currentItems, totalItems, scrollOutItems;
        String token = "";
        SpinKitView progress;
        Context context;
        SearchView searchView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            recyclerView = (RecyclerView) findViewById(R.id.postList);
            manager = new LinearLayoutManager(this);
            adapter = new PostAdapter(this, items);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
            progress = (SpinKitView) findViewById(R.id.spin_kit);

            setUpToolbar();

            // Navigation Menu Start//
            navigationView = (NavigationView) findViewById(R.id.navigation_menu);
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {


                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.nav_home: {
                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                        }
                        break;
                        case R.id.nav_downloads: {
                            Intent intent = new Intent(getApplicationContext(), DlActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                        }
                        break;

                        case R.id.nav_settings: {
                            Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                        }
                        break;
                        case R.id.nav_contact_us: {
                            Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                        }
                        break;
                        case R.id.nav_policy: {
                            Intent intent = new Intent(getApplicationContext(), PolicyActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                        }
                        break;
                        case R.id.nav_share: {
                            final String appPackageName = getApplication().getPackageName();
                            String shareBody = "Download " + getString(R.string.app_name) + " From :  " + "http://play.google.com/store/apps/details?id=" + appPackageName;
                            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                            sharingIntent.setType("text/plain");
                            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
                            startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.app_name)));
                        }
                        break;
                        case R.id.nav_rate: {
                            final String appPackageName = getApplication().getPackageName();
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                            } catch (android.content.ActivityNotFoundException anfe) {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
                            }
                        }
                        break;
                        case R.id.nav_exit: {
                            finish();
                        }
                    }


                    return false;
                }
            });
            /// Navigation menu End ///


            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                        isScrolling = true;
                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    currentItems = manager.getChildCount();
                    totalItems = manager.getItemCount();
                    scrollOutItems = manager.findFirstVisibleItemPosition();

                    if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
                        isScrolling = false;
                        getData();
                    }
                }
            });


            getData();

            if (!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
            else {

            }

        }

        private void setUpToolbar() {
            drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
            drawerLayout.addDrawerListener(actionBarDrawerToggle);
            actionBarDrawerToggle.syncState();
        }

        protected void getData() {
            String url = BloggerApi.url + "?key=" + BloggerApi.key;
            if (token != "") {
                url = url + "&pageToken=" + token;
            }
            if (token == null) {
                return;
            }

            progress.setVisibility(View.VISIBLE);
            final Call<PostList> postList = BloggerApi.getService().getPostList(url);
            postList.enqueue(new Callback<PostList>() {
                @Override
                public void onResponse(Call<PostList> call, Response<PostList> response) {
                    PostList list = response.body();
                    token = list.getNextPageToken();
                    items.addAll(list.getItems());
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                    progress.setVisibility(View.GONE);
                }

                @Override
                public void onFailure(Call<PostList> call, Throwable t) {
                    Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
                }
            });

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.menu2, menu);

            MenuItem search = menu.findItem(R.id.action_search);
            SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
            search(searchView);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            return super.onOptionsItemSelected(item);
        }

        private void search(SearchView searchView) {

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

                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {

                    if (adapter != null) adapter.getFilter().filter(newText);
                    return true;
                }
            });
        }

        public boolean isConnected(Context context) {

            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netinfo = cm.getActiveNetworkInfo();

            if (netinfo != null && netinfo.isConnectedOrConnecting()) {
                android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
                    return true;
                else return false;
            } else
                return false;
        }

        public AlertDialog.Builder buildDialog(Context c) {

            AlertDialog.Builder builder = new AlertDialog.Builder(c);
            builder.setTitle("No Internet Connection");
            builder.setMessage("Please switch on your Mobile Data or Wifi Connection. Press ok to Exit");

            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    finish();
                }
            });

            return builder;
        }
}

0 个答案:

没有答案