(Deprecated) Fragment onOptionsItemSelected not being called

后端 未结 9 2142
孤城傲影
孤城傲影 2020-11-28 20:45

EDIT: This question was for the deprecated sherlock action bar. Android support library should be used instead now

I have added an action bar menu o

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 21:39

    I have noticed that the solution people gave you was to implement the code for your menue item in the activity rather then the fragment. I think it will look much more orgenized if you had implemented the code in the fragment rather then the activity 'cos in my opinion it looks better. To do so, do as follows :

    Activity

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
            getMenuInflater().inflate(R.menu.menu, menu);      
            return true;
        }
    
     @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {            
            switch (item.getItemId())
            {
                case R.id.SomeIDInTheMenueOfTheActivity:
                {
                   //something();
                    break;
                }
                default:
                 //do something default and add the code under : 
                 return super.onOptionsItemSelected(item);
            }
            return true;
        }
    

    Fragment

     @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);  
                setHasOptionsMenu(true);      
            }
    
      @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
        {           
            super.onCreateOptionsMenu(menu, inflater);
        }
    
         @Override
            public boolean onOptionsItemSelected(MenuItem item)
            {
                switch (item.getItemId())
                {           
                    case R.id.SomeIDInFragmentMenue:
                    {             
                        break;
                    }
    
                    default:
                        return super.onOptionsItemSelected(item);
                }
    
                return true;
            }
    

    Now the lines (and the likes): "return super.onOptionsItemSelected(item);" in the activity and fragment are super important, because as if you will follow the code in debug, you will see that the menue events functions will be called first on the Activity, and if the item did not match the id's in the activity's switch-case, the degault line : "super.onOptionsItemSelected(item);" will call the onOptionsItemSelected function on the fragment, as we wanted. (if you have many fragments, make sure to have that line in them as well, as the calling hirarchy can be somewhat complicated).

提交回复
热议问题