Android动态更新Menu菜单的实现过程

  public class MainActivity extends AppCompatActivity {

  //默认为网格模式

  private boolean isShowGridModeIcon = true;

  //网格菜单 和 列表菜单

  private MenuItem gridMenuItem;

  private MenuItem listMenuItem;

  //用字符串来表示当前的文件列表显示模式

  private TextView viewModeStatus;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  Toolbar toolbar = findViewById(R.id.toolbar);

  setSupportActionBar(toolbar);

  viewModeStatus = findViewById(R.id.textview_refresh);

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

  // Inflate the menu; this adds items to the action bar if it is present.

  getMenuInflater().inflate(R.menu.menu_main, menu);

  Log.e("test", "=====MenuTest onCreateOptionsMenu=====");

  gridMenuItem = menu.findItem(R.id.sub_menu_grid);

  listMenuItem = menu.findItem(R.id.sub_menu_list);

  return true;

  }

  @Override

  public boolean onPrepareOptionsMenu(Menu menu) {

  Log.e("test", "=====MenuTest onPrepareOptionsMenu=xxxx====");

  MenuItem aboutMenuItem = menu.findItem(R.id.action_about);

  // (3个点)【更多】菜单中把 关于 设置为不可点击

  aboutMenuItem.setEnabled(false);

  if (isShowGridModeIcon) {

  gridMenuItem.setVisible(true);

  listMenuItem.setVisible(false);

  viewModeStatus.setText("当前为网格模式");

  } else {

  gridMenuItem.setVisible(false);

  listMenuItem.setVisible(true);

  viewModeStatus.setText("当前为列表模式");

  }

  return super.onPrepareOptionsMenu(menu);

  }

  @Override

  public boolean onOptionsItemSelected(MenuItem item) {

  // Handle action bar item clicks here. The action bar will

  // automatically handle clicks on the Home/Up button, so long

  // as you specify a parent activity in AndroidManifest.xml.

  int id = item.getItemId();

  Log.e("test", "=====MenuTest onOptionsItemSelected= sssss ====");

  //noinspection SimplifiableIfStatement

  if (id == R.id.action_settings) {

  return true;

  } else if (id == R.id.sub_menu_grid) {

  /*1. 点击网格图标,界面中文件布局显示变成网格模式*/

  //伪代码:setViewMode(State.MODE_GRID);

  isShowGridModeIcon = false;

  /*2. 图标变成切换list图标*/

  invalidateOptionsMenu();

  } else if (id == R.id.sub_menu_list) {

  /*1.点击列表图标,界面中文件布局显示变成列表模式*/

  //伪代码:setViewMode(State.MODE_LIST);

  isShowGridModeIcon = true;

  /*2. 图标变成切换grid图标*/

  invalidateOptionsMenu();

  }

  return super.onOptionsItemSelected(item);

  }

  }