将 ActionBar 按钮可见性设置为 GONE

Setting an ActionBar button visibility to GONE

我有一个带有一些操作栏按钮的工具栏。如果 Build.VERSION.SDK_INT < 21.

在以下菜单文件中,我定义了操作栏按钮:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>

<item
    android:id="@+id/addons"
    android:icon="@drawable/ic_add_box_black_24dp"
    android:title="camera"
    app:showAsAction="always"/>


<item
    android:id="@+id/hellosearch"
    android:icon="@drawable/ic_search_black_24dp"
    android:title="camera"
    app:showAsAction="always"/>

//在 MainActivity 中我覆盖了方法:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.addons:
            //we are requesting to purchase something:
            Log.d("billing009","trying to start a purchase!! user has accesss(subs): "+user_has_autorenew_subs+
                    " didFind :: " + didFindTotalAccess);

          showPurchaseDialog(styled_title);
            //inHouseMethod_StartPurchase();
            break;

        case R.id.hellosearch:
            mDrawer.openDrawer(GravityCompat.START);
            return true;

但是,当用户点击其中一个操作栏按钮时调用此方法。

如何使用在 onCreate: 中创建的工具栏对象来获取相机图标(ActionBar 按钮),以便在 Build.VERSION.SDK_INT < 21 时将其可见性设置为 GONE?

//inside onCreate
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); 

您可以在 onCreateOptionsMenu 中执行此操作,例如

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.your_menu_xml, menu);
        if(Build.VERSION.SDK_INT < 21) {
           MenuItem item = menu.findItem(R.id.idOfYourMenuItem);
           item.setVisible(false);
        }
        return true;
    }

将此方法放入您的 Activity

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem camera = menu.findItem(R.id.addons);      
    if(Build.VERSION.SDK_INT < 21) 
    {           
        camera.setVisible(true);
    }
    else
    {
        camera.setVisible(false);
    }
    return true;
}

onPrepareOptionsMenu Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

onCreateOptionsMenu() 被调用一次。
onPrepareOptionsMenu() 每次打开菜单时调用。

来自 onCreateOptionsMenu() 文档:

This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu).