1
重写Activity的onCreateOptionsMenu()方法
- @Override
- public
boolean onCreateOptionsMenu(Menu menu) { -
MenuInflater inflater = getMenuInflater(); -
inflater.inflate(R.menu.main, menu); -
return super.onCreateOptionsMenu(menu); } -
2
响应Action按钮的点击事件
当用户点击Action按钮的时候,系统会调用Activity的onOptionsItemSelected()方法,通过方法传入的MenuItem参数,我们可以调用它的getItemId()方法和menu资源中的id进行比较,从而辨别出用户点击的是哪一个Action按钮,
- @Override
- public
boolean onOptionsItemSelected(MenuItem item) { -
switch (item.getItemId()) { -
case R.id.action_compose: -
Toast.makeText(this, "Compose", Toast.LENGTH_SHORT).show(); -
return true; -
case R.id.action_delete: -
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show(); -
return true; -
case R.id.action_settings: -
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show(); -
return true; -
default: -
return super.onOptionsItemSelected(item); -
} - }