The problem you are experiencing is related to setting the menus that make up the Action Bar in each Fragment. It looks like you are using the same action bar menu file for different Ragments, so the search item appears in the other Ragments you open. To solve the problem, create different menu files for each Fragment, so you don’t need to get "deleting" the unwanted items in other Fragments. Ex.:
Suppose two Factions Frag1 and Frag2 and two menu files, frag_menu1.xml and frag_menu2.xml;
define the files frag_menu1.xml and frag_menu2.xml and then in each Ragment enter the method setHasOptionsMenu(true)
in the 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 which xml will be used as a menu through the method onCreateOptionsMenu(Menu menu, MenuInflater inflater)
. In the case of Frag2 using the menu file frag_menu2.xml, will look 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
}
Then set the operations for each menu item clicked using the method onOptionsItemSelected(MenuItem item)
, which must 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 Fragment ( and menu) as you change Fragment, you must add the current Fragment to the Fragments stack before calling the next one. This is done through the method addToBackStack()
. Therefore, before committing your transaction, add the current Ragment to the stack as follows:
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
.addToBackStack()
.commit();
But using this solution, I can not keep the status of the search and list, IE, when you back Frag2, Frag 1 will not have search view open with the query and filtered listing
– Kiotto
@Kiotto, I modified the answer in case of maintaining the state of Fragment
– regmoraes
Thanks for the answer, but it doesn’t work... Go from Fraga to B the action bar changes as I want, but doing back, the list is no longer filtered by the query used before
– Kiotto