how to set toolbar on FragmentActivity? - android

I want to set toolbar on my activity which extends FragmentActivity. I know that for use setSuppoertActionBar(toolbar) method we extends AppCompatActivity instead of FragmentActivity but I override the onMenuItemSelected(int featureId, MenuItem item) method which is final in AppCompatActivity and final method cannot override. so I'm restricted to extends FragmentActivity.
Here is my code:
public class MainActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar); -> error is here
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, item);
}
I saw many answers related to that question but everyone says extends AppCompatActivity instead of FragmentActivity but I want to set toolbar as well as override onMenuItemSelected(int featureId, MenuItem item) method.
what should I do, please help.

This thing is good when you are using NavigationDrawer
use this:-
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
then set Toolbar Title according to different fragment with different Titles in onNavigationItemSelected :-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
sfm = getSupportFragmentManager();
Fragment fragment = new Fragment();
int id = item.getItemId();
if (id == R.id.nav_id) {
fragment = new YourFragment();
toolbar.setTitle("SET TOOLBAR NAME");
}else if (id == R.id.nav_id2) {
fragment = new YourFragment();
toolbar.setTitle("SET TOOLBAR NAME");
}
For single fragment, first customize your style.xml like this :-
<style name="YourStyleName" parent="Theme.AppCompat.Light.DarkActionBar">
// ToDo as you want to do or as per your requirement
</style>
then apply into your custom toolbar:-
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/YourStyleName" >
// ...........
</android.support.v7.widget.Toolbar>

You can also create your own toolbar:
First set up the main theme to extend Theme.AppCompat.Light.NoActionBar
<style name="style_1" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
Remember to apply the theme:
#Override
protected void onCreate(Bundle savedInstanceState) {
this.setTheme(R.style.style_1);
// ...
}
then in your Activity's xml you can set your own custom toolbar:
<include layout="#layout/my_toolbar"/>
where #layout/my_toolbar may look like this:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/toolbar_height"
app:contentInsetStart="0dp"
app:layout_collapseParallaxMultiplier="1.0">
<!-- insert your views here -->
</android.support.v7.widget.Toolbar>

First set style as
<style name="style_1" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
then
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Home");

You should extend your Activity from AppCompatActivity as this includes support for Fragments and the Toolbar.
And then override the
onCreateOptionsMenu() and onOptionsItemSelected() methods
You shouldn't be overriding
onMenuItemSelected()
public class MainActivity extends AppCompatActivity { ...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentTransaction ft = getSupportFragmentManager.beginTransaction();
....
....
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}

Related

Android menu with ActionBarDrawerToggle

I have a simple task:
Create a menu with few items which opens on a toggle action bar button.
My activity_main is:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mt.gmtelandroid.MainActivity"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
>
</android.support.design.widget.NavigationView>
and navigation menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/meni1" >
<item android:id="#+id/navhome"
android:title="Home"
android:icon="#mipmap/ic_home_black_24dp"
>
</item>
<item android:id="#+id/navtasks" android:title="Zadaci"
android:icon="#mipmap/ic_drive_eta_black_24dp"
></item>
<item android:id="#+id/navlogout" android:title="Odjava"
android:icon="#mipmap/ic_close_black_24dp">
</item>
<item android:id="#+id/myname" android:title="Moj Nalog"
android:icon="#mipmap/ic_account_circle_black_24dp">
</item>
Main activity is
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtogle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mtogle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open_menu, R.string.close_menu);
mDrawerLayout.addDrawerListener(mtogle);
mtogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mtogle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't know how to add a listener onMenuItemClick so I can handle what happens when a user clicks on a menu item.
I have tried adding some code to onOptionsItemSelected method, but when I was debuging it I found out that this method is only called on toggle buton click, not on menu item click!?
You have to implement the callbacks for NavigationView.OnNavigationItemSelectedListener in Activity as below,
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
than handle click event of NavigationView like below code
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent i;
if (id == R.id.navhome) {
// perform your action here
} else if (id == R.id.navtasks) {
// perform your action here
} else if (id == R.id.navlogout) {
// perform your action here
}else if (id == R.id.myname) {
// perform your action here
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Try to add:
callback implements NavigationView.OnNavigationItemSelectedListener,
It will override onNavigationItemSelected(MenuItem item) {... }. You can put your click code here by item.getItemId().
I hope this helps you.

start a new layout when click on items in navigation drawer

I have a MainActivity.java and NavigationDrawer. I want to when I click on items in navdrawer, start new layout. I know I can start new Activity, but I don't want a new activity. new layout is suitable for me. is this possible???
this is my ActivityMain.java:
public class MainActivity extends AppCompatActivity {
public Toolbar toolbar;
protected DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.a1);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_more_vert_black_24dp);
navigationView = (NavigationView) findViewById(R.id.a2);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setChecked(true);
drawerLayout.closeDrawer(Gravity.RIGHT);
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.khat) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
}
else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
return super.onOptionsItemSelected(item);
}
else {
Toast.makeText(getApplicationContext(),"SOMETHING",Toast.LENGTH_LONG).show();
}
return true;
}
public void onBackPressed(){
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)){
drawerLayout.closeDrawer(Gravity.RIGHT);
}else {super.onBackPressed();}
}
}
and this is my second layout that I want start when I click on items:`
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#132740"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:textColor="#FFFFFF"
android:id="#+id/textView"
android:textSize="22sp"
android:layout_marginTop="20dp"
android:text="blah blah"/>
</RelativeLayout>
is this possible?
If is just the layout you wanna to change, there is a very simple soluction:
if (Case_A)
setContentView(R.layout.layout1);
else if (Case_B)
setContentView(R.layout.layout2);
But considering using Fragments:
https://developer.android.com/guide/components/fragments.html
With fragments, you will be able to divide your code in multiples class, for each layout. It will be more readable and light:
Here is an example
Use fragment in order to user multiple layout with different operation. If u just want to change the layout then u can set new layout on item click with setContentView(new layout); .

Action bar options are not showing in android studio

enter image description hereI am new to android, right now I am referring the sunshine app by udacity.com tutorials. The code is the same, but still it is not showing the option settings and doesn't refresh on the action bar
How could I resolve my problem?
MainActivity. java code for main menu
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and ForecastFragment.java for refresh menu
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
the main menu xml file code
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.sunshine.app.MainActivity" >
<item android:id="#+id/action_settings"
android:orderInCategory="100" />
app:showAsAction="never"
android:title="#string/action_settings"
android:orderInCategory="100" /></menu>
the refresh menu is in forecastfragment.xml file code for refrsh menu is
<item android:id="#+id/action_refresh"
app:showAsAction="never"
android:title="#string/action_refresh"
android:orderInCategory="100" />
the manifest file is
<application android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
the style.xml file
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="android:icon">#drawable/ic_launcher</item>
</style>
<!--style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style-->
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
In your fragment's onCreateView method write
setHasOptionsMenu(true);
and add this super.onCreateOptionsMenu(menu, inflater); to your onCreateOptionsMenu
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.forecastfragment, menu);
}
you can add this below code in your activity_main.xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.Toolbar>
and this in your MainActivity.java
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(mToolbar);
Your complete MainActivity should look like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(mToolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//setHasOptionsMenu(true);
return rootView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
}
}
}
and if you want to show your refresh menu then you need to put this code in your fragment setHasOptionsMenu(true);
and you activity_main.xml can be like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="20dp"
android:paddingRight="20dp" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.Toolbar>
<FrameLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.MainActivity"
tools:ignore="MergeRootFrame" />
</LinearLayout>
it should work...
In your menu.xml you have to set app:showAsAction="always" and it will show.
Material design does'nt support ActionBar. So you cannot see ActionBar as well as App icon. If you want ActionBar like functionality then you can use toolbar like the following code does...
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
Extend you baseClass from ActionBarActivity class.
This should take care of this issue.
public class MainActivity extends ActionBarActivity{
}

Calling Toolbar on each Activity

My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?
Create a Base class for Activity
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
configureToolbar();
}
protected abstract int getLayoutResource();
private void configureToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getSupportFragmentManager();
if (fm != null && fm.getBackStackEntryCount() > 0) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
finish();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.
At last don't forget to include the ToolBar in each activity layout.
Edit:
Override that method getLayoutResource() in each Activity and pass the layout id.
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public int getLayoutResource() {
return R.layout.activity_main;
}
This is my implementation. It removes the need of the getLayoutResources() from the accepted answer and brings back the "setContentView()" in all activities as normal
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected boolean useToolbar() {
return true;
}
#Override
public void setContentView(int layoutResID) {
View view = getLayoutInflater().inflate(layoutResID, null);
configureToolbar(view);
super.setContentView(view);
}
private void configureToolbar(View view) {
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
if (toolbar != null) {
if (useToolbar()) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
toolbar.setVisibility(View.GONE);
}
}
}
}
From here on you just extend BaseActivity. If you don't want a toolbar you will have to override the useToolbar().
Don't forget to add in activity.xml at the top
<include layout="#layout/toolbar" />
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</merge>
It depends on your implementation but if you want avoid boilerplate code you should use good programming OO.
An Example using Fragment.
public abstract class FragmentBase extends Fragment {
protected void settingsToolbar(View rootView) {
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
// TODO add your code and your requirements
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
I hope this can give you an idea.
If you have used Activity then Create BaseActivity that extends AppCompatActivity or ActionBarActivity(Deprecated) and move Toolbar code to BaseActivity.
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
If you have used Fragment then Create BaseFragment that extends Fragment and move Toolbar code to BaseFragment.
public class BaseFragment extends Fragment {
View main;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = inflater.inflate(R.layout.fragment_about, container, false);
Toolbar toolbar = (Toolbar) main.findViewById(R.id.toolbar);
getActivity().setSupportActionBar(toolbar);
return main;
}
}
In main XML layout you have to add Toolbar xml code.
Now in every view(Activity) extends BaseActivity instead of AppCompatActivity or ActionBarActivity so you can get access Toolbar in every view.
public class YourActivity extends BaseActivity{
//your code
}
EDIT1:
main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:theme="#style/toolbarTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/green"
android:minHeight="?attr/actionBarSize" />
</RelativeLayout>
EDIT2:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
add these two lines below setSupportActionBar(toolbar); in BaseActivity.
I hope it helps!
Create a base activity and initialize your tool bar in this class. Now it can be extends to all other child activity.
FirtActivity extends BaseActivity
SecondActivity extends BaseActivity
In base activity toll bar back button click you can check like below mentioned way
if(this instance of FirstActivity){
//do stuff here
}else if(this instance of SecondActivity){
//do stuff here
}

onCreateOptionsMenu not called when starting new activity

My onCreateOptionsMenu works only in my MainActivity and when I try to put another onCreateOptionsMenu in another activity to inflate a different menu it does not display my menu bar (note that I have it setup exactly the same in both activities).
I do not get any errors, it just does not display my menu bar on my secondary activity.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.expanded_view_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//noinspection SimplifiableIfStatement
int id = item.getItemId();
if (id == R.id.action_back) {
finish();
}
return super.onOptionsItemSelected(item);
}
Also note that I changed getMenuInflater() to super.getMenuInflater() and got same result.
In case you are using tool bar in your activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
}
try adding method of super in your callback onCreateOptionsMenu implementation.
return super.onCreateOptionsMenu(menu);
The problem in my case is if extend Activity, then onCreateOptionsMenu is not triggered. Did it manually with in onCreate:
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main);
Of course, toolbar is defined in CoordinatorLayout
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"/>
</android.support.design.widget.AppBarLayout>
don't forget to call parent function like this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
....
}
you should building a new xml menu (Second.xml).
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);//Second es your new xml.
return true;
}
I was having the same problem: - I found the solution that worked for me.
1>Check to what you extend class: - In my case, I have tried my activity with extending AppCompatActivity class and the menu is showing proper and when I changed it to activity class then it stopped displaying.
Not Working: -
public class GridViewActivity extends Activity
2>Try to extend your class with AppCompatActivity class instead of activity class.
Working: -
public class GridViewActivity extends AppCompatActivity
Call setHasOptionsMenu(true) from onCreate.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

Categories

Resources