In my main activity I have my action bar. How can this stay visible even if I launch a new activity?
Does the new activity have to extend my main activity for this to work?
If you declare the onCreateOptionMenu
method, wich is the one where you put the elements in the actionbar, in you main activity (A), all the other activities that extend A without re-declaring that method will have the same actionbar of A.
Android menu options provide user with actions and other options to choose from the action bar of the screen. Some of these actions are common to all the activities for your application, so instead of creating them in each of your activities you can create a BaseActivity that extends the Activity class and does all your menu processing. Then you can extend then base activity class in your application activities to get the same menu options.
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends BaseActivity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button nextActivity = (Button) findViewById(R.id.nextActivity);
nextActivity.setOnClickListener(this);
}
}
Here is BaseActivity Class
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class BaseActivity extends Activity{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.common_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Do Code Here
default:
return super.onOptionsItemSelected(item);
}
}
}
I hope it helps you .
You can use the same implementation pattern (inheritance/composition) I described here
Global "search function" in whole app
for the search functionality. Just do what I described there with the onCreateOptionMenu Method to have the sameone for all activities without needing to write the same boring three lines of code in each activity.