首先定义一下menu文件
xmlns:app="http://schemas.android.com/apk/res-auto">
android:id="@+id/edit_and_save"
app:showAsAction="always"
android:title="修改"
android:icon="@android:drawable/ic_menu_edit"
/>
然后需要在Activity文件中设置menu菜单, 需要重写onCreateOptionsMenu方法设置显示菜单
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
getMenuInflater().inflate(R.menu.activity_menu,menu);
mMenuActionBar=menu;
returnsuper.onCreateOptionsMenu(menu);
}
完整的dome:
publicclassMainActivityextendsAppCompatActivity{
privatebooleanisEdit=false;
privateTextViewmEditText;
privateMenuItemmMenuItem;
privateMenumMenuActionBar;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText=(TextView)findViewById(R.id.edit_text);
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
getMenuInflater().inflate(R.menu.activity_menu,menu);
mMenuActionBar=menu;
returnsuper.onCreateOptionsMenu(menu);
}
@Override
publicbooleanonOptionsItemSelected(MenuItemitem){
switch(item.getItemId()){
caseR.id.edit_and_save:
if(isEdit){
update();
}else{
update();
}
returntrue;
default:
returnsuper.onOptionsItemSelected(item);
}
}
privatevoidupdate(){
mMenuItem=mMenuActionBar.findItem(R.id.edit_and_save);
mMenuItem.setChecked(true);
if(isEdit){
mMenuItem.setIcon(android.R.drawable.ic_menu_edit);
mEditText.setEnabled(false);
}else{
mMenuItem.setIcon(android.R.drawable.ic_menu_save);
mEditText.setEnabled(true);
}
isEdit=!isEdit;
}
}