Start a new Fragment when searching

Asked

Viewed 74 times

0

I need to know how when people give enter in the search bar, the application pass what was typed to another Fragment and start it.

Currently I arrived at the following code, but it is not working.

@Override
       public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

           inflater.inflate(R.menu.pesquisa, menu);
           super.onCreateOptionsMenu(menu,inflater);
                   //Pega o Componente.  
           SearchView mSearchView = (SearchView) menu.findItem(R.id.search)
                   .getActionView();
           //Define um texto de ajuda:
                   mSearchView.setQueryHint("teste");
                   if (Intent.ACTION_SEARCH.equals(getActivity().getIntent().getAction())) {
                       Intent intent = null;
                    String query = intent.getStringExtra(SearchManager.QUERY);
                     }
           // exemplos de utilização:
                   doMySearch(query);

           return;

       }


       public void doMySearch(String query) {
Search serach = new Search();
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
Bundle bundle = new Bundle();
bundle.putString("QUERY",query);
serach.setArguments(bundle);      

}

1 answer

3


I think your code is a bit confusing but I’ll try to help.

This method only defines which menu will be displayed when the user clicks on the options:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}

This method is called when the user clicks on a menu item:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
    case R.id.new_game:
        action1();
        return true;
    case R.id.help:
        action2();
        return true;
    default:
        return super.onOptionsItemSelected(item);
}
}

Your Fragment must have the following static method to allow an instantiation with passing parameters:

public static DetailsFragment newInstance(String parametro) {
    DetailsFragment f = new DetailsFragment();

    Bundle args = new Bundle();
    args.putString("key", parametro);
    f.setArguments(args);

    return f;
}

And you’re gonna set it calling it in your Activity:

 MyFragment frag = MyFragment.newInstance("parametro");
 getSupportFragmentManager().beginTransaction().replace(R.id.container_do_fragment, frag).commit();

To recover this parameter in Fragment you do the following:

getArguments().getString("key");

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.