See action bar across all activities - Android

纵饮孤独 提交于 2019-12-18 13:33:32

问题


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?


回答1:


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.




回答2:


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 .




回答3:


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.



来源:https://stackoverflow.com/questions/11779340/see-action-bar-across-all-activities-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!