How to insert onCreateOptionsMenu into a Java class?

0

How do I insert onCreateOptionsMenu and onOptionsItemSelected into a Java class so I do not get repeating on all the Activities that call it?

I have to pass only the ids and classes that I call by clicking on the menu item.

@Override
public boolean onCreateOptionsMenu(Menu menu){

MenuInflater MenuItem = getMenuInflater();
// Aqui deve-se passar o xml como parametro da função para a outra classe
MenuItem.inflate(R.menu.novo_menu,menu); 

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


switch(item.getItemId()){
    case R.id.id_c:

         // Aqui deve-se passar as 2 classes pela função para colocar no Itent
         Intent tela = new Intent(Tela1.this, tela2.class);
         startActivity(tela);
         break;

    case R.id.id_s:
        // Aqui deve-se passar as 2 classes pela função para colocar no Itent
        Intent tela = new Intent(Tela1.this, tela3.class);
        startActivity(tela);
        break;
}


return super.onOptionsItemSelected(item);
}
    
asked by anonymous 01.07.2018 / 15:05

1 answer

1

As I said, if you use fragments, they will all have the parent activity, in it you implement the 2 methods, if you case for each fragment you want options to have a different function, you can do this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if(tal_fragment.isVisible()){
        switch (id) {
            case R.id.item1:
              //Seu código
            default:
                return super.onOptionsItemSelected(item);
    }else if(outro_fragment.isVisible()){
            switch (id) {
                case R.id.item1:
                    //Seu código
                default:
                    return super.onOptionsItemSelected(item);
    }
}

See? Depending on which fragment is currently open, the items have different functions. I do not know if this is what you want, but give feedback.

If what you want is just that your NavigationDrawer and Menu are visible in all fragments , it's the same thing, but I believe their functions will be the same, these methods you implement in the parent activity.

    
01.07.2018 / 21:02