SearchView in ActionBar using Fragments

只愿长相守 提交于 2021-01-29 01:31:16

问题


I have a navigation drawer in HomeActivity. Inside the navigation I have fragments that contain different RecycleViews each. I want to implement SearchView in ActionBar so it will search in the RecycleView according to the active fragment.

This is on of the fragments code:

   
   public class HomeFragment extends Fragment {

    private static BackEnd backEnd;
    private RecyclerView rvBooks;
    private BookAdapter adapter;
    private MenuItem mSearchAction;
    private SearchView searchView;
    private ActionBar actionBar;
    private boolean isSearchOpened = false;
    private EditText etSearch;

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        rvBooks = (RecyclerView) view.findViewById(R.id.rv_books);
        rvBooks.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new BookAdapter(getActivity());
        rvBooks.setAdapter(adapter);
        try {
            backEnd = BackEndFactory.getInstance(getActivity());
            for(int i = 0; i < 10; i++)
            {
                backEnd.addBook(new Book(R.mipmap.ic_launcher, "Genere "+(i+1), "Book "+(i+1), "2015", "Author", 100));
            }
            adapter.setBookList(backEnd.getBooksList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

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

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.home, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_search:
                handleMenuSearch();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        mSearchAction = menu.findItem(R.id.action_search);
        searchView = (SearchView) mSearchAction.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                adapter.clearData();
                adapter.setBookList(backEnd.searchForBook(query));
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    private void handleMenuSearch() {
        actionBar = getSupportActionBar(); //get the actionbar

        if(isSearchOpened){ //test if the search is open
            if(actionBar != null)
            {
                actionBar.setDisplayShowCustomEnabled(false);   //disable a custom view inside the actionbar
                actionBar.setDisplayShowTitleEnabled(true);     //show the title in the action bar
            }

            // hides the keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);

            // add the search icon in the action bar
            mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search));

            isSearchOpened = false;
        } else { // open the search entry
            if(actionBar != null)
            {
                actionBar.setDisplayShowCustomEnabled(true); //enable it to display a
                // custom view in the action bar.
                // action.setCustomView(R.layout.search_bar);//add the custom view

                actionBar.setDisplayShowTitleEnabled(false); //hide the title
            }
            // open the keyboard focused in the edtSearch
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT);
            // add the close icon
            mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search));

            isSearchOpened = true;
        }
    }
}

I have problems in handleMenuSearch() function: getSupportActionBar() and getSystemService(Context.INPUT_METHOD_SERVICE) are not recognized because fragments are not activities.

So please, how to do it correct?


回答1:


You need to get the actual parent context (which is the parent Activity) by calling getActivity() as follows:

getActivity().getSupportActionBar();
...
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
...


来源:https://stackoverflow.com/questions/34134594/searchview-in-actionbar-using-fragments

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