The problem you are having is related to the definition of the menus that make up the Action Bar in each Fragment. It looks like you're using the same action bar menu file for different fragments, so the search item appears in the other fragments you open. To solve the problem, create different menu files for each fragment, so you do not have to "delete" the unwanted items in other fragments. Ex.:
Suppose two fragments Frag1 and Frag2 and two menu files, frag_menu1.xml and frag_menu2.xml ;
Set the frag_menu1.xml and frag_menu2.xml files and then in each fragment insert the method setHasOptionsMenu(true)
into OnCreate
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); //define que o fragment terá um menu próprio
// Seu código
}
Then, for each fragment, define what will be the xml used as a menu using the onCreateOptionsMenu(Menu menu, MenuInflater inflater)
method. In the case of Frag2 using the frag_menu2.xml menu file, it looks like this:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.frag_menu2,menu); //define o arquivo de menu
}
Next, define the operations for each item of the menu clicked using the onOptionsItemSelected(MenuItem item)
method, which should be declared in the corresponding fragment, in the case of Frag2 , the method would look like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.item_1_do_menu_frag_menu2:
//seu código
break;
}
return super.onOptionsItemSelected(item);
}
If you want to keep the current state of the fragment (and the menu) as you change the fragment, you must add the current fragment in the stack of fragments before calling the next one. This is done using the addToBackStack()
method. Therefore, before committing your transaction, add the current fragment in the stack as follows:
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
.addToBackStack()
.commit();