2013-11-09 110 views
75

如何以編程方式更改ActionBar中的MenuItem圖標?我嘗試使用如何以編程方式更改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) 

回答

185

您不能在onCreate()的菜單項上使用findViewById(),因爲菜單佈局尚未充氣。你可以創建一個全局的Menu變量並在onCreateOptionsMenu()中初始化它,然後在你的onClick()中使用它。

private Menu menu; 

在你onCreateOptionsMenu()

this.menu = menu; 

在您的按鈕的onClick()方法

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

怎麼樣的一個片段,在沒有onCreateOptionsMenu()? – AlleyOOP

+0

您可能需要從您的片段 –

+0

@LithithMohan上調用您的活動中的方法,我嘗試了相同的操作,但它不起作用。我雖然可以改變菜單項的標題的字體顏色,但我無法更改圖標。我已經發布我的問題在這裏:http://stackoverflow.com/questions/36716450/setting-icons-to-the-menu-items –

3

我解決了這個問題是這樣的:

onCreateOptionsMenu

this.menu = menu; 
this.menu.add("calendar"); 
ImageView imageView = new ImageView(getActivity()); 
imageView.setMinimumHeight(128); 
imageView.setMinimumWidth(128); 
imageView.setImageDrawable(yourDrawable); 
MenuItem item = this.menu.getItem(0); 
item.setActionView(imageView); 

onOptionsItemSelected

if (item.getOrder() == 0) { 
    //TODO 
    return true; 
} 
29

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(getResources().getDrawable(R.drawable.ic_launcher)); 

    return super.onPrepareOptionsMenu(menu); 
} 
0

相反getViewById(),請使用

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

與你的菜單項ID替換Menu.FIRST

2

這適用於我。它應該是在你的onOptionsItemSelected(MenuItem item)方法item.setIcon(R.drawable.your_icon);

-1

其工作

 MenuItem tourchmeMenuItem; // Declare Global ....... 

public boolean onCreateOptionsMenu(Menu menu) 
{ 
     getMenuInflater().inflate(R.menu.search, menu); 
     menu.findItem(R.id.action_search).setVisible(false); 
     tourchmeMenuItem = menu.findItem(R.id.done); 
     return true; 
} 

    public boolean onOptionsItemSelected(MenuItem item) { 

    case R.id.done: 
         if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){ 
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
           mScannerView.setFlash(false); 
           LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false); 
           tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32)); 
          } 
         }else { 
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
           mScannerView.setFlash(true); 
           LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true); 
           tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32)); 
          } 
         } 
         break; 

} 
相關問題