Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See action bar across all activities - Android

Tags:

android

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?

like image 446
panthro Avatar asked Aug 02 '12 14:08

panthro


2 Answers

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.

like image 199
rciovati Avatar answered Oct 22 '22 15:10

rciovati


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 .

like image 5
IntelliJ Amiya Avatar answered Oct 22 '22 16:10

IntelliJ Amiya