Start a new Fragment when searching

0

I need to know how when people give enter in the search bar, the application passes what was typed to another fragment and starts it.

Currently I have 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);      

}
    
asked by anonymous 11.04.2015 / 05:21

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 parameter passing:

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'll set it by 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 the vc fragment, do the following:

getArguments().getString("key");

I hope I have helped.

    
11.04.2015 / 18:43