2014-03-31 43 views
0

我需要獲取對操作欄中項目的引用。我想訪問它onCreate獲取操作欄的項目?

int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0); 
    Item item = // getItem? 
    if (silent_mode == 1) { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on)); 
    } 
    else { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off)); 
    } 

任何想法?

回答

0

做的工作在onCreateOptionsMenu()代替,那麼這將是accessable:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 

    ... 


    MenuItem item = menu.findItem(R.id.YOUR_ID); 
    int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0); 
    if (silent_mode == 1) { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on)); 
    } 
    else { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off)); 
    } 

    return true; 

} 
+0

謝謝!這樣可行。這個問題真的是我無法在onCreate中使用mnMenu! – Philip

1

onCreateOptionsMenu(Menu menu)將菜單的引用存儲在類級變量中。就像這樣:

Menu mnMenu; 

public boolean onCreateOptionsMenu(Menu menu) { 
    .... 
    .... 
    mnMenu = menu; 
    return true; 
} 

private void someMethod() { 
    int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0); 
    MenuItem item = mnMenu.findItem(R.id.action) //R.id.action is the id of your MenuItem 
    if (silent_mode == 1) { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on)); 
    } 
    else { 
     item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off)); 
    } 
} 
+0

(;忘了,對不起,你能告訴我爲什麼「MN」經常被用來前綴展示一些東西,比如mnMenu? – Philip

+1

這只是一種知道對象是什麼類型的方法(至少我是用它的)在一個巨大的程序中,可能有許多代碼行,以便查看保存在你可能不得不上下滾動以查看該對象是哪種類型,但通過在這些字符前加上這些字符,我們可以很容易地知道(或回憶)該對象是什麼類型 – EdmDroid

+0

例如,我使用「字符串」,「TextView」使用「tv」,使用「EditText」使用「et」,使用「ListView」使用「lv」。你可以自己命名;它根本沒關係:) – EdmDroid