问题描述
我的项目中有 10-15 个活动.我希望在所有活动中都有选项菜单.然后是他们的任何方式,我们可以在一个地方完成它并出现在所有活动中.
I have 10-15 activities in my project. I want to have the option menu mostly in all Activities. Then is their any way we can do it at one place and it appears in all activities.
另外,我想隐藏一些选项菜单.那么,是否有可能或者我必须在所有活动中编写选项菜单代码.
Also, I will like to hide the option menu in some. So, is it possible or I have to write option menu code in all activities.
问候
苏尼尔
推荐答案
创建一个扩展 Activity 的类(比如 BaseActivity),并覆盖 onCreateOptionsMenu
和 onOptionsItemSelected
函数.
Create a Class (say BaseActivity) that extends Activity, and override onCreateOptionsMenu
and onOptionsItemSelected
functions.
public class BaseActivity extends Activity {
// Activity code here
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item:
// do what you want here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
现在,在其他 15-16 个 Activity 中,您应该扩展 BaseActivity,而不是扩展一个 Activity.
Now, in the other 15-16 activities, instead of extending an Activity, you should extend BaseActivity.
public class FooActivity extends BaseActivity {
// Activity code here
}
这样,您的所有活动都会派生出选项菜单.对于您希望禁用选项菜单的活动,您可以在该特定活动中再次覆盖它.
This way, all your activities derive the options menu. For activities where you want the options menu disabled, you can override it again in that particular activity.
public class BarActivity extends BaseActivity {
// Activity code here
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Do Nothing
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Do Nothing
}
}
希望它不会在清单文件中给您带来问题.
Hopefully, it doesn't give you problems in the manifest file.
这篇关于Android 中所有活动中的相同选项菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!