如何在Android Fragment工具栏上创建搜索视图?

时间:2018-05-31 15:57:02

标签: android fragment searchview

我正在开发一个应用程序,它从json接收数据并且我想应用searchview进行过滤目的我实现了onQueryTextChange和onQueryTextSubmit方法。我遇到的问题当我搜索它时没有显示任何事情我不知道什么是幸福任何人帮助我请如何实施searchview。 这是我的片段类

public class Restaurant extends Fragment{

RecyclerView restaurant_recycler;
RestaurantsAdapter adapter;
private ProgressDialog sweetProgressDialog;
SessionManager sessionManager;
List<Restaurant_model> itemrestaurants;
List<String> mAllValues;
private Context mContext;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View v = inflater.inflate(R.layout.activity_restaurant, container, false);

    restaurant_recycler = (RecyclerView) v.findViewById(R.id.recycler_view_restaurant);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    itemrestaurants = new ArrayList<>();
    adapter = new RestaurantsAdapter(getContext(), itemrestaurants);
    restaurant_recycler.setLayoutManager(mLayoutManager);
    restaurant_recycler.setItemAnimator(new DefaultItemAnimator());

    restaurant_recycler.setAdapter(adapter);
    sweetProgressDialog = new ProgressDialog(getContext(), R.style.MyAlertDialogStyle);

    sessionManager = new SessionManager(getContext());

    show_restaurants();
    return v;
}

private void show_restaurants() {
    RequestQueue queue = Volley.newRequestQueue(getContext());
//        sweetProgressDialog = ProgressDialog.show(NewsFeed.this, "Loading Postss", "Please Wait...",false,false);

    StringRequest myReq = new StringRequest(Request.Method.POST,
            Config.URL_show_restaurants, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (sweetProgressDialog.isShowing()) {
                sweetProgressDialog.dismiss();
            }
            if (response.isEmpty() || response == null || response.equals("0")) {
                sweetProgressDialog.dismiss();
                Toast.makeText(getActivity(), "Error Loading Restaurants, check your connection.", Toast.LENGTH_LONG).show();
                return;
            }
            try {
                //sweetProgressDialog.dismiss();
                Log.e("tag", "response " + response);
                JSONArray array = new JSONArray(response);

                for (int i = 0; i < array.length(); i++)

                {
                    JSONObject thisOBj = (JSONObject) array.get(i);
                    itemrestaurants.add(new Restaurant_model(thisOBj.getString("id"), thisOBj.getString("name"),
                            thisOBj.getString("address"),
                            thisOBj.getString("image")));

                }
                adapter.notifyDataSetChanged();

            } catch (JSONException e) {
                if (sweetProgressDialog.isShowing()) {
                    sweetProgressDialog.dismiss();
                }
                Log.i("myTag", e.toString());
                Toast.makeText(getContext(), "Parsing error", Toast.LENGTH_SHORT).show();

            }

        }

    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("myTag", error.toString());
                    if (sweetProgressDialog.isShowing()) {
                        sweetProgressDialog.dismiss();
                    }
                    Toast.makeText(getContext(), "Server Error", Toast.LENGTH_SHORT).show();
                }
            }) {



    myReq.setRetryPolicy(new DefaultRetryPolicy(
            20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
    ));
    myReq.setShouldCache(false);
    queue.add(myReq);
    sweetProgressDialog = new ProgressDialog(getContext());
    sweetProgressDialog.setMessage("Loading Restaurants...");
    sweetProgressDialog.show();
}

@SuppressLint("ResourceType")
@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    MenuItem mSearchMenuItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = null;
    if (mSearchMenuItem != null) {
        searchView = (SearchView) mSearchMenuItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                String result = query;
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toLowerCase();
                List<Restaurant_model> filteredList = new ArrayList<>();

                for (Restaurant_model row : itemrestaurants) {
                    if (row.getRestaurant_name().toLowerCase().contains(newText.toLowerCase()) || row.getRestaurant_address().contains(newText)) {
                        filteredList.add(row);
                    }
                    adapter.setFilter(itemrestaurants);

                }
                return true;
            }

        });

    }

}

}

2 个答案:

答案 0 :(得分:0)

更改您的代码

@Override
        public boolean onQueryTextChange(String newText) {
            newText = newText.toLowerCase();

            List<Restaurant_model> filteredList = filter(itemrestaurants, newText);

                adapter.setFilter(itemrestaurants);

            }
            return true;
        }

添加以下方法

private List<Restaurant_model> filter(List<Restaurant_model> models, String query) {
    query = query.toLowerCase();final List<Restaurant_model> filteredModelList = new ArrayList<>();
    for (HomeFeedItem model : models) {
        final String text = model.getTitle().toLowerCase();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}

试试这个希望它正在运作

答案 1 :(得分:0)

您的代码需要一些修复

<强> Function For Filtering:-

 private List<Restaurant_model> filtered(String search_query) {
       List<Restaurant_model> filteredModelList = new ArrayList<>();
       for (Restaurant_model row : itemrestaurants) {
            Boolean contains =row.getRestaurant_name().toLowerCase().contains(search_query.toLowerCase()) || row.getRestaurant_address().contains(search_query)
            if (contains) {
                filteredModelList.add(row);
            }
        }
        return filteredModelList;
    }

<强> Function Implementation:-

@Override
        public boolean onQueryTextChange(String newText) {
            newText = newText.toLowerCase();

            List<Restaurant_model> filteredList = filtered(newText);

                adapter.setFilter(filteredList);

            }
            return true;
        }