如何以编程方式更改ActionBar中的MenuItem图标

时间:2013-11-09 20:04:23

标签: java android

如何以编程方式更改ActionBar中的MenuItem图标?我试着用

  

MenuItem menuItem =(MenuItem)findViewById(R.id.action_settings);   menuItem.setIcon(getResources()。getDrawable(R.drawable.ic_launcher))

但它不起作用。 这是我的代码:

MainActivity

package com.test;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MenuItem menuItem = (MenuItem)findViewById(R.id.action_settings);
                menuItem.setIcon(getResources().getDrawable(R.drawable.ic_launcher));
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

main.xml中

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

    <item
        android:icon="@drawable/action_settings"
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="always"/>
</menu>

activity_main

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">
    <Button
        android:id="@+id/button"
        android:text="Set icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

这是我跑完后的例外情况:

MenuItem menuItem = (MenuItem)findViewById(R.id.action_settings);


11-09 19:52:40.471    1735-1735/com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ClassCastException: android.support.v7.internal.view.menu.ActionMenuItemView
            at com.test.MainActivity$1.onClick(MainActivity.java:19)
            at android.view.View.performClick(View.java:2485)
            at android.view.View$PerformClick.run(View.java:9080)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)

8 个答案:

答案 0 :(得分:228)

您不能在onCreate()中的菜单项上使用findViewById(),因为菜单布局尚未膨胀。您可以创建一个全局Menu变量并在onCreateOptionsMenu()中初始化它,然后在onClick()中使用它。

private Menu menu;

在你的onCreateOptionsMenu()

this.menu = menu;

在按钮的onClick()方法

menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));

答案 1 :(得分:41)

Lalith的回答是正确的。

您也可以尝试这种方法:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            invalidateOptionsMenu();
        }
    });

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem settingsItem = menu.findItem(R.id.action_settings);
    // set your desired icon here based on a flag if you like
    settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher)); 

    return super.onPrepareOptionsMenu(menu);
 }

答案 2 :(得分:6)

这对我有用。它应该在您的onOptionsItemSelected(MenuItem item)方法item.setIcon(R.drawable.your_icon);

答案 3 :(得分:2)

使用

代替getViewById()
MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);

用您的菜单项ID替换Menu.FIRST

答案 4 :(得分:1)

科特林版本:

toolbar.menu.findItem(R.id.notification).icon =
                    ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)

toolbar.menu.findItem(R.id.notification).isVisible = true

答案 5 :(得分:0)

onMenuItemClick(MenuItem item)中使用 只需invalidateOptionsMenu(); item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_baseline_play_circle_outline_24px));

答案 6 :(得分:0)

这是我解决此问题的方法:

1-创建一个字段变量,例如:private Menu mMenuItem;

2-覆盖方法invalidateOptionsMenu():

@Override
public void invalidateOptionsMenu() {
    super.invalidateOptionsMenu();
}

3-在您的invalidateOptionsMenu()中调用方法onCreate()

4-像这样在您的mMenuItem = menu中添加onCreateOptionsMenu(Menu menu)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.webview_menu, menu);
    mMenuItem = menu;
    return super.onCreateOptionsMenu(menu);
}

5-在方法onOptionsItemSelected(MenuItem item)中,像这样更改所需的图标:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){

        case R.id.R.id.action_settings:
            mMenuItem.getItem(0).setIcon(R.drawable.ic_launcher); // to change the fav icon
            //Toast.makeText(this, " " + mMenuItem.getItem(0).getTitle(), Toast.LENGTH_SHORT).show(); <<--- this to check if the item in the index 0 is the one you are looking for
            return true;
    }
    return super.onOptionsItemSelected(item);
}

答案 7 :(得分:-1)

正在运作

{{1}}