Android - How to access actionbar's menu items in fragment class

前端 未结 5 1660
别那么骄傲
别那么骄傲 2020-12-08 19:29

How should I access the actionbar\'s menu items in fragment ? I have tried this but nothing happened

@Override
public boolean onOptionsItemSelected(MenuItem          


        
5条回答
  •  暖寄归人
    2020-12-08 19:52

    One thing I would add to this (my reputation does not allow me to comment) and reason it was not working for me.

    Make sure your fragment's hosting activity extends AppCompatActivity not FragmentActivity!

    public class MainActivity extends AppCompatActivity {
    
    }
    

    From the Google Reference Documentation for FragmentActivity:

    Note: If you want to implement an activity that includes an action bar, you should instead use the ActionBarActivity class, which is a subclass of this one, so allows you to use Fragment APIs on API level 7 and higher.

    ActionBarActivity now being deprecated, use AppCompatActivity instead. When using AppCompatActivity, also make sure you set "the activity theme to Theme.AppCompat or a similar theme" (Google Doc too).

    android.support.v7.app.AppCompatActivity is a subclass of the android.support.v4.app.FragmentActivity class (see AppCompatActivity ref doc).

提交回复
热议问题