Action bar : get view element

2019-07-13 22:37发布

问题:

I am implementing Action bar compoment.

my res/menu/action_menu.xml which holds two items to be shown on Action Bar:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item 
          android:id="@+id/help_me"
          android:icon="@drawable/help"
          android:showAsAction="always"/>

    <item 
          android:id="@+id/log_out"
          android:icon="@drawable/logout"
          android:showAsAction="always"/>

</menu>

In my Activity:

public class MyActivity extends FragmentActivity{

     @Override
     protected void onCreate(Bundle arg0) {
        super.onCreate(arg0); 
        ...
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_menu, menu);
        return true;
    }

}

I would like to fetch the @+id/help_me icon from action bar < item > and add onClickListener to it, based on my above code in Activity, where and how can I fetch the @+id/help_me icon and add the listener ??

回答1:

you can use menu.findItem(R.id.help_me) and an OnMenuItemClickListener. Bear in mind that unless you're doing anything special with the menu item, you should use the standard callbacks built into the Activity