---
# System prepended metadata

title: 動態改變 Options Menu
tags: [Options Menu]

---

動態改變 Options Menu
===

```java=
String menuString = ""; // "red" or "green"

menuString = "red";
invalidateOptionsMenu(); // 觸發 onPrepareOptionsMenu() 重新繪製新的 options menu

```

```java=
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    menu.clear();
    MenuInflater inflater = getMenuInflater();
    
    // 根據 menuString, 來選擇不同的佈局檔重新繪製
    if(menuString=="red"){
        inflater.inflate(R.menu.red_menu, menu);
    }
    else if(menuString=="green"){
        inflater.inflate(R.menu.green_menu, menu);
    }
    
    return true;
}
```
## Ref.
[How to replace menu dynamically with another in Android](https://stackoverflow.com/questions/32071475/how-to-replace-menu-dynamically-with-another-in-android)

###### tags: `Options Menu`