ActionBarCompat

布局文件中添加menu

menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:support="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/menu_setting"
android:icon="@mipmap/ic_action_settings"
android:title="@string/menu_setting"
support:showAsAction="never"/>
<item
android:id="@+id/menu_refresh"
android:icon="@mipmap/ic_action_refresh"
android:title="@string/menu_refresh"
support:showAsAction="always"/>
</menu>

Activity中添加menu

values/ids.xml
<resources>
<item name="menu_location" type="id"/>
</resources>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
MenuItem location=menu.add(0,R.id.menu_location,0,"Location");
location.setIcon(R.mipmap.ic_action_location);
MenuItemCompat.setShowAsAction(location,MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_setting:
return true;
case R.id.menu_location:
return true;
case R.id.menu_refresh:
return true;
}
return super.onOptionsItemSelected(item);
}

用法

运行时更改菜单项

mButtonForbidRefresh.setOnClickListener(new View.OnClickListener() {
private int i=0;
@Override
public void onClick(View view) {
i++;
if(i%2==1)
mButtonForbidRefresh.setActivated(true);
else
mButtonForbidRefresh.setActivated(false);
invalidateOptionsMenu();
}
});
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item=menu.findItem(R.id.menu_refresh);
if(mButtonForbidRefresh.isActivated()){
item.setEnabled(false);
} MenuItem location = menu.add(0, R.id.menu_location, Menu.CATEGORY_SECONDARY, "Location");
location.setIcon(R.mipmap.ic_action_location);
MenuItemCompat.setShowAsAction(location, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); return super.onPrepareOptionsMenu(menu);
}

menu.findItem(int id)

menu.getItem(int index)

onPrepareOptionsMenu(Menu menu)和onCreateOptionsMenu(Menu menu)区别

onCreateOptionsMenu(Menu menu)只在最初的时候会调用每次点击menu都会调用一次onPrepareOptionsMenu(Menu menu).使用invalidateOptionsMenu()会直接调用onPrepareOptionsMenu(Menu menu);

上一篇:无网络环境下安装Dynamics CRM


下一篇:loj6157 A ^ BProblem (并查集)