他のすべてのアクティビティが拡張する基本アクティビティを作成したくない、または作成できない場合は、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 メソッドを静的にしたくない場合がありますが、これは機能するはずです。