This question doesn't really have much to do with Android. This is about how you can re-use code multiple places.
You could use inheritance for this purpose.
Say you have 3 different activities, but you want them to have a set of common features - in your case the ActionBar
.
In that case you could create an abstract class
that implements the ActionBar
and make all your activities inherit from this abstract class
.
The hierarchy could look something like this:
public abstract class BaseActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.oncreate(savedInstanceState);
// Setup your common ActionBar here.
}
}
Now for this abstract class
to do its work, you'll have to make all your activities inherit from this, like so:
public class MyActivityA extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.oncreate(savedInstanceState); // It's important to call through to super to have it setup the ActionBar for the current activity.
// Next call setContentView(R.layout.my_activity_layout);
// And what else you need to do.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_a_menu, menu);
return true;
}
}
And for the next Activity
you do the same:
public class MyActivityB extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.oncreate(savedInstanceState);
// Next call setContentView(R.layout.my_activity_layout);
// And what else you need to do.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_b_menu, menu);
return true;
}
}
The onCreateOptionsMenu
is implemented in all your activities, as to create different menu items and the same should go for your onOptionsItemSelected
.
Now this is a very basic example of how to share basic features for multiple classes and it should be something you'd have to be knowledgable about before you start working with Android, as the above code is common Java.
Also keep in mind, that it's a very broad question you're asking.
I actually just wanted to put this in a comment, but decided it would become too large to fit into the comments.