ive got 2 activities with option menus. the option menus exists of 4 menu items. 3 of them (option1, option2 and option3) exist in both option menus. the option menus distinguish between the 4th menu item (option4 in activity1 and option5 in activity2).
Is there in Android an opportunity to outsource the 3 same options in - for example a OptionMenuHelper class - and access it from the 2 activities so that i dont have to implement 2 times exactly the same methods in onOptionsItemSelected(MenuItem)?
thanks in advice
pebbles
1st Update
example:
I want to outsource exportAsCSV() so i can access it from my 2 activities
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ...
case R.id.om_export:
exportAsCSV();
return true;
case ...
}
return super.onOptionsItemSelected(item);
}
and the exportAsCSV includse a cursor which gets data from a Content Provider over getContentResolver. and the ContentResolver cant be static :/
private void exportAsCSV() {
...
Cursor cursor = getContentResolver().query(MyQueries.CONTENT_URI_ALL,
new String[]{Column1, Column2},
"", null, Column1);
....
}
2nd Update
Okay I solved it:
public class MenuHelper {
Context context;
public ExportHelper(Context con) {
context=con;
}
public void exportAsCSV() {
...
Cursor cursor = context.getContentResolver().query(MyQueries.CONTENT_URI_ALL,
new String[]{Column1, Column2},
"", null, Column1);
...
}
}
Well this way isnt static (what was my intention) but its working. Now i can access it from every activity i want by creating an object...
Thank you anyway
(If u know a solution how to do that in static, let me know ;) )
greets
I don't really see the advantage of that, except that you don't want to have boilerplate code. You absolutely can write an static helper method, that does inflation of the menu.xml.
I would just write one menu.xml and decide in onCreateOptionsMenu()
of the two activities which items are to be shown. It's not that much code. For example like this:
@Override
public void onCreateOptionsMenu ( Menu menu, MenuInflater inflater ) {
inflater.inflate(R.menu.shared_menu, menu);
MenuItem item5 = menu.findItem(R.id.item_5);
// hide in activity 2
if(item5 != null)
item5.setVisible(false);
// static helper call
MenuHelper.initActiviyMenu(this, menu, inflater);
}
...
public class MenuHelper {
public static void initActivity( Activity activity, Menu menu, MenuInflater inflater ){
inflater.inflate(R.menu.shared_menu, menu);
if(activity instanceof ActivityA){
// do stuff, hide items, content provider
}
if(activity instanceof ActivityB){
// do stuff, hide items, content provider
}
}
}