How to enable shared code in android

I am creating an am android application that has 4 different actions having a common menu. To display the menu in all actions, usually I need to add this code to each file.

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } 

In any case, can I add this code to a single file and include it in all actions?

Thanks in advance.

+4
source share
2 answers

Create one Main Activity write your menu code in this action, and then extend other actions with the main activity.

 public MainActivity extends Activity { @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return false; } } 

And some TempActivity

 public TempActivity extend MainActivity { /...... } 
+7
source
 abstract class MenuHavingActivity extends Activity { @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } } 

and then your other actions extend the MenuHavingActivity function

edit: yes what user370305 said

+2
source

Source: https://habr.com/ru/post/1390165/


All Articles