如果您不想或无法创建一个基本 Activity 来让其他所有 Activity 扩展 - 为什么没有一个实用程序类,它有一个public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {...}
函数和一个public static boolean onOptionsItemSelected(MenuItem item) {...}
?
public class Utils {
public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater ){
//... create default options here
}
public static boolean onOptionsItemSelected(MenuItem item) {
//... see if you want to handle the selected option here, return true if handled
}
}
然后从你的活动中你可以这样做:
public class YourActivity extends Activity {
// ...
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater ){
Utils.onOptionsItemSelected(menu, inflater);
//... add other options here
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean handled = Utils.onOptionsItemSelected(item);
if (!handled) {
switch(item.getItemId()) {
case R.id.menu_sign_out:
//... deal with option
break;
//.. deal with other options
}
}
return handled;
}
您可能希望根据您将其构建到应用程序中的方式来更改它的确切实现 - 即您可能不希望 utils 方法是静态的,因为您可能需要在其中维护一些状态,但这应该可以工作。