Android Search menu item disappears when pressing back button/collapsing search field - java

I'm using android SearchView to have a search button in my action bar. I followed this tutorial from Google Developers on YouTube, and added a few tweaks based on my own needs. However, whenever I exit the search field that comes up when clicking the button, the search button disappears!
Here is my onCreateOptionsMenu and onOptionsItemSelected functions
onCreateOptionsMenu:
#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;
}
onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(final 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();
switch (id) {
case R.id.action_settings:
// TODO: settings activity
break;
case R.id.action_logout:
FirebaseAuth.getInstance().signOut();
break;
case R.id.action_search:
// Initialize everything here, because it produces a NullPointerException if initialized in onCreateOptionsMenu
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
ComponentName componentName = new ComponentName(this, SearchableActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
break;
}
return super.onOptionsItemSelected(item);
}
And here's my menu_main.xml layout file
<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.magnus.inline.MainActivity">
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_logout"
android:orderInCategory="200"
android:title="#string/action_logout"
app:showAsAction="never" />
And searchable.xml layout file
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</searchable>
Images
EDIT:
I noticed that the only time the search button disappears is when I've pressed the options button while in "search mode"(see the last image in link). I have a feeling that when the options menu is displayed, the "action_search" is somehow converted to a options menu item, instead of an action bar item (?). For anyone asking, whenever I try to call MenuItemCompat.getActionView() of a searchview MenuItem in the onCreateOptionsMenu function, my app just crashes and says that it tries to perform it on a null object reference.
Here's my activity_main.xml layout file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.magnus.inline.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/main_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AlertDialog.AppCompat.Light"
android:background="#color/colorPrimaryDark" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Instead of
app:showAsAction="ifRoom|collapseActionView"
Change to
app:showAsAction="always|collapseActionView

Related

Can not go to onOptionsItemSelected in Android studio

I follow the tutorial https://www.youtube.com/watch?v=iEXh1-KVeVc&t=213s for making bottom menu.
Then i use onCreateOptionsMenu and onOptionsItemSelected to set action when click in, but it still not working.
Here is my menu code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/leftNav"
android:icon="#drawable/ic_baseline_stars_24"
android:title="News"/>
<item
android:id="#+id/home"
android:title=""/>
<item
android:id="#+id/rightNav"
android:icon="#drawable/ic_baseline_menu_24"
android:title="Menu"/>
</menu>
MainActivity.java code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu
getMenuInflater().inflate(R.menu.bottom_nav_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.leftNav:
// Left nav
Toast.makeText(this,"Click left",Toast.LENGTH_LONG);
return true;
case R.id.rightNav:
return true;
case R.id.home:
Toast.makeText(this,"Click home", Toast.LENGTH_LONG);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
activity_main xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".MainActivity">
<com.google.android.material.bottomappbar.BottomAppBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:id="#+id/bottomAppBar"
app:fabCradleMargin="10dp"
app:fabCradleRoundedCornerRadius="10dp"
app:fabCradleVerticalOffset="10dp">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigationView"
android:layout_marginRight="16dp"
app:menu="#menu/bottom_nav_menu"
android:background="#drawable/transparent_background"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"
android:src="#drawable/ic_baseline_sports_basketball_24"
app:layout_anchor="#id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Any one can help me, i'm new with android studio. Thanks in advance

Menu won't show in Activity

I have a menu that won't show up in my activity. I have a main activity and a separate activity that contains a list of items I want the user to be able to search through. However, the menu isn't showing up in the activity for searching, so nothing happens when entering in a string for the search.
The goal was the get the menu in the search activity in order to allow the user to search through items using a SearchView and RecyclerView
I'm very new to Android Studio, so any help would be greatly appreciated.
Here is the menu for the SearchView
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
<item android:id="#+id/action_search2"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
Here is the layout xml
<?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="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<include
layout="#layout/activity_search_toolbar"/>
<android.support.v7.widget.SearchView
android:id="#+id/action_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:menu="#menu/search_menu">
</android.support.v7.widget.SearchView>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme">
<Button
android:id="#+id/GoBackbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO BACK" />
<!--<android.support.v7.widget.SearchView-->
<!--android:id="#+id/searchBar"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content">-->
<!--<!–app:menu="#menu/search_menu"–>-->
<!--</android.support.v7.widget.SearchView>-->
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
and the toolbar to add to the layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/search_toolbar"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
Here is where I inflate the search_menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
Finally this is part of my Adapter class to filter the items in a RecyclerView
#Override
public Filter getFilter() {
return locationFilter;
}
private Filter locationFilter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint){
List<Location> filteredLocationList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredLocationList.addAll(locationListFull);
} else{
String filterPattern = constraint.toString().toLowerCase().trim();
for(Location location : locationListFull){
if(location.getTitle().toLowerCase().contains(filterPattern)){
filteredLocationList.add(location);
}
// Add another if statement here if we want to be able to search
// descriptions as well
}
}
FilterResults results = new FilterResults();
results.values = filteredLocationList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results){
locationList.clear();
locationList.addAll((List)results.values);
notifyDataSetChanged();
}
};
Also if there's another way to use the SearchView with RecyclerView besides creating a menu for the SearchView, that would be very helpful. I have tried researching ways to access the SearchView besides through creating a new menu, but haven't found anything useful.
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
https://developer.android.com/reference/android/app/Activity.html#onPrepareOptionsMenu(android.view.Menu)
You need to override onPrepareOptionsMenu and setup your searchview there instead of doing that in onCreateOptionsMenu

Actionbar icons not beeing updated

I am trying to change an icon in the actionbar, but I can not get it work. If I send to the log the getIcon().toString(), It seems that the icon is modified, but the actionbar is not updated.
This is the main activity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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=".MainActivity"
tools:layout_editor_absoluteY="81dp">
<android.support.v7.widget.Toolbar
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/AppTheme">
</android.support.v7.widget.Toolbar>
The menu xml file:
<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=".MainActivity">
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<item
android:id="#+id/about"
android:title="#string/about"
android:orderInCategory="110"
app:showAsAction="never" />
<item
android:id="#+id/connect"
android:title="Connect"
android:icon="#drawable/ic_play"
android:orderInCategory="130"
app:showAsAction="always" />
<item
android:id="#+id/testin"
android:title="Test_in"
android:icon="#drawable/ic_testin"
android:orderInCategory="120"
app:showAsAction="always" />
And the main activity code:
//Menu Items
MenuItem testinMenu, connectMenu;
Menu actionMenu;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Action Bar
toolbar = findViewById( R.id.appbar);
setSupportActionBar( toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menumain, menu);
actionMenu = menu;
connectMenu = (MenuItem) menu.findItem(R.id.connect);
testinMenu = (MenuItem) menu.findItem(R.id.testin);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.connect: {
connectMenu.setIcon( R.drawable.ic_stop);
invalidateOptionsMenu();
if( isRainbowConnected == false) {
connect();
} else
disconnect();
break;
}
case R.id.testin: {
if( isRainbowConnected == true)
sendTestIn();
break;
}
// case blocks for other MenuItems (if any)
}
return true;
}
I have tried everything, but nothing seems to work.
Thanks in advance!

How to set menu to Toolbar in Android

I want use ToolBar instead of ActionBar, but don't show me menu in toolbar!!! i want set menu such as Refresh or Setting buttons in ActionBar.
Toolbar.xml code :
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:navigationContentDescription="#string/abc_action_bar_up_description"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Main Page"
android:gravity="center"/>
MainPage.java code:
public class MainPage extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Main Page");
}
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_menu);
}
}
main_menu.xml code :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_main_setting"
android:icon="#drawable/ic_settings"
android:orderInCategory="100"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
<item
android:id="#+id/menu_main_setting2"
android:icon="#drawable/ic_settings"
android:orderInCategory="200"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
</menu>
How to fix this problem and show menu in Toolbar ? thanks all dears <3
just override onCreateOptionsMenu like this in your MainPage.java
#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, menu);
return true;
}
Don't use setSupportActionBar(toolbar)
I don't know why but this works for me.
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_menu);
For menu item click do this:
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.item1) {
// do something
} else if (item.getItemId() == R.id.filter) {
// do something
} else {
// do something
}
return false;
}
});
Will update the why part of this answer when I find a proper explanation.
Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.
1. Make a menu xml
This is going to be in res/menu/main_menu.
Right click the res folder and choose New > Android Resource File.
Type main_menu for the File name.
Choose Menu for the Resource type.
Paste in the following content as a starter.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_add"
android:icon="#drawable/ic_add"
app:showAsAction="ifRoom"
android:title="Add">
</item>
<item
android:id="#+id/action_settings"
app:showAsAction="never"
android:title="Settings">
</item>
</menu>
You can right click res and choose New image asset to create the ic_add icon.
2. Inflate the menu
In your activity add the following method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
3. Handle menu clicks
Also in your Activity, add the following method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_add:
addSomething();
return true;
case R.id.action_settings:
startSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Further reading
Android Menu Documentation
You need to override this code in your Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu, this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
and set your toolbar like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can still use the answer provided using Toolbar.inflateMenu even while using setSupportActionBar(toolbar).
I had a scenario where I had to move toolbar setup functionality into a separate class outside of activity which didn't by-itself know of the event onCreateOptionsMenu.
So, to implement this, all I had to do was wait for Toolbar to be drawn before calling inflateMenu by doing the following:
toolbar.post {
toolbar.inflateMenu(R.menu.my_menu)
}
Might not be considered very clean but still gets the job done.
First way:
In activitymain.xml
<androidx.appcompat.widget.Toolbar
android:id="#+id/maintoolbar"
android:layout_width="match_parent"
android:layout_height="56dp"/>
In MainActivity.java
import androidx.appcompat.widget.Toolbar;
private Toolbar toolbar;
Inside onCreate method-
toolbar=findViewById(R.id.maintoolbar);
setSupportActionBar(toolbar);
Inside your MainActivity class-
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<your menu xml file name here>,menu);
return super.onCreateOptionsMenu(menu);
}
Second way :
//Remove setSupportActionBar(toolbar) and onCreateOptionmenu.
toolbar=findViewById(R.id.maintoolbar);
toolbar.inflateMenu(R.menu.<your menu xml file name here>);
Also you need this, to implement some action to every options of menu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_help:
Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
Without ActionBar but with Toolbar
If you want to use a Toolbar instead of the ActionBar, to setSupportActionBar is contradiction in principle as #RohitSingh answered above.
You need neither to use setSupportActionBar nor to override onCreateOptionsMenu and onOptionsItemSelected which are used for the ActionBar.
NoActionBar theme
Place a Toolbar in the layout xml
Prepare a menu xml
Toolbar#inflateMenu (alternatively you can also set a menu in the layout xml)
Toolbar#setOnMenuItemClickListener
Below is an example.
1. NoActionBar theme
(MaterialCompolent.DayNight theme is used in this sample)
<style name="Theme.AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
2. Place a Toolbar in the layout
(MaterialToobar is used in this sample)
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
3. Prepare a menu xml
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"
app:showAsAction="ifRoom" />
<item
android:id="#+id/item2"
android:title="#string/item2"
app:showAsAction="ifRoom" />
</menu>
4. Toolbar#inflateMenu
binding.toolbar.inflateMenu(R.menu.main); // binding is a ViewBinding
5. Toolbar#setOnMenuItemClickListener
Recent Android recommend to avoid to use switch to differentiate ids. Using a normal if ~ else if ~ else block is desirable. In addition to that, we can use lambda in Java 8.
binding.toolbar.setOnMenuItemClickListener(menuItem -> {
int itemId = menuItem.getItemId();
if (itemId == R.id.item1) {
// do something for item1
return true;
} else if (itemId == R.id.item2) {
// do something for item2
return true;
} else {
// if you do nothing, returning false should be appropriate.
return false;
}
});
Although I agree with this answer, as it has fewer lines of code and that it works:
How to set menu to Toolbar in Android
My suggestion would be to always start any project using the Android Studio Wizard. In that code you will find some styles:-
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
and usage is:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<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/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Due to no action bar theme declared in styles.xml, that is applied to the Main Activityin the AndroidManifest.xml, there are no exceptions, so you have to check it there.
<activity android:name=".MainActivity" android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The Toolbar is not an independent entity, it is always a child
view in AppBarLayout that again is the child of
CoordinatorLayout.
The code for creating a menu is the standard code since day one,
that is repeated again and again in all the answers, particularly
the marked one, but nobody realized what is the difference.
BOTH:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
AND:
How to set menu to Toolbar in Android
WILL WORK.
Happy Coding :-)
In XML add one line inside
<com.google.android.material.appbar.MaterialToolbar app:menu="#menu/main_menu"/>
In java file
Remove three line setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle("Main Page"); }
add one line toolbar.setTitle("Main Page")
In your activity override this method.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
This will inflate your menu below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_main_setting"
android:icon="#drawable/ic_settings"
android:orderInCategory="100"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
<item
android:id="#+id/menu_main_setting2"
android:icon="#drawable/ic_settings"
android:orderInCategory="200"
app:showAsAction="always"
android:actionLayout="#layout/toolbar"
android:title="Setting" />
</menu>
In my case, I'm using an AppBarLayout with a CollapsingToolbarLayout and the menu was always
being scrolled out of the screen, I solved my problem by switching android:actionLayout in menu's XML to
the toolbar's id. I hope it can help people in the same situation!
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="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=".activities.MainScreenActivity"
android:screenOrientation="portrait">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="300dp"
app:elevation="0dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="exitUntilCollapsed|scroll"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="48dp"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:elevation="0dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
main_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/logoutMenu"
android:orderInCategory="100"
android:title="#string/log_out"
app:showAsAction="never"
android:actionLayout="#id/toolbar"/>
<item
android:id="#+id/sortMenu"
android:orderInCategory="100"
android:title="#string/sort"
app:showAsAction="never"/> </menu>
You can achieve this by two methods
Using XML
Using java
Using XML
Add this attribute to toolbar XML
app:menu = "menu_name"
Using java
By overriding onCreateOptionMenu(Menu menu)
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.demo_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
for more details or implementating click on the menu go through this article
https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/
You don't actually need to touch the fragment/activity class at all to get a menu inside a toolbar. You can use Rohit Singh's method inside onViewCreated method
import androidx.appcompat.widget.Toolbar
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar = view.findViewById<Toolbar>(R.id.inbox_toolbar)
toolbar.inflateMenu(R.menu.inbox_menu)
}
or
simply define a app:menu element inside the toolbar,
<androidx.appcompat.widget.Toolbar ...
app:menu= "#menu/myMenu" ?>
Simple fix to this was setting showAsAction to always in menu.xml in res/menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/add_alarm"
android:icon="#drawable/ic_action_name"
android:orderInCategory="100"
android:title="Add"
app:showAsAction="always"
android:visible="true"/>
</menu>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar;
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_drawer,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_drawer){
drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
} else {
drawerLayout.openDrawer(GravityCompat.END);
}
}
return super.onOptionsItemSelected(item);
}
res/layout/drawer_menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_drawer"
android:title="#string/app_name"
android:icon="#drawable/ic_menu_black_24dp"
app:showAsAction="always"/>
</menu>
toolbar.xml
<com.google.android.material.appbar.AppBarLayout
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:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:titleTextColor="#android:color/white"
app:titleTextAppearance="#style/TextAppearance.Widget.Event.Toolbar.Title">
<TextView
android:id="#+id/toolbar_title"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/app_name"
android:textColor="#android:color/white"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title" />
</androidx.appcompat.widget.Toolbar>
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
*// here is where you set it to show on the toolbar*
setSupportActionBar(toolbar);
}
Well, you need to set support action bar setSupportActionBar(); and pass your variable, like so: setSupportActionBar(toolbar);

Android: Change actionbar icon after click and change it back after onCreate()

I try to change the icon of the action bar to a progress bar in onOptionsItemSelected(MenuItem) method.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.progressitem2:
mProgress = item;
mProgressCreate = mProgress;
mProgress.setActionView(R.layout.progress);
mLayout.removeView(mTable);
// Execute code that change mTable again.
return true;
}
progress.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:focusable="true"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
style="#android:style/Widget.ProgressBar.Small"/>
</LinearLayout>
The action bar is created in this way:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar, menu);
mProgress = menu.getItem(0);
mProgressCreate = mProgress;
return true;
}
action_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/progressitem2"
android:icon="#drawable/ic_action_refresh"
android:title="Reload"
android:showAsAction="ifRoom|withText"
android:visible="true" />
</menu>
This works good. The progress icon is shown after I click the action bar icon.
I try to keep the reference of the original action bar symbol in mProgressCreate and try to add the action view back at the end of the onCreate() method:
mProgress.setActionView(mProgressCreate.getActionView());
But this do not work...
What`s wrong here?
Regards,
Sandro
I found the solution. I simply forgot to call invalidateOptionsMenu() before I reset the action view with mProgress.setActionView(mProgressCreate.getActionView());
invalidateOptionsMenu();
mProgress.setActionView(mProgressCreate.getActionView());
And everything is working fine :-).

Categories

Resources