Set no item pre-selected in Bottom Navigation view - android

I'm adding the new Bottom Navigation View from the material design library to a project, and I would like to have no pre selected item by default.
For now first item is selected by default.
I have used
mBottomNavigation.getMenu().getItem(0).setChecked(false);
but when doing it in for loop for all the menu item last item is selected again by default.
Is there a way we can achieve this?

Not sure about the proper way to achieve this but a work around will help-
setCheckable(false) for first item
navigation.getMenu().getItem(0).setCheckable(false);
item.setCheckable(true) inside onNavigationItemSelected()
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
item.setCheckable(true);
mTextMessage.setText(R.string.title_home);
return true;
}
return false;
}

I came up with another solution
Just add one more item to your menu.xml file for example
This is my bottom_nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/home" />
<item
android:id="#+id/navigation_cart"
android:icon="#drawable/ic_shopping_cart_black_24dp"
android:title="#string/cart" />
<item
android:id="#+id/navigation_wishlist"
android:icon="#drawable/ic_favorite_border_black_24dp"
android:title="#string/wish_list" />
<item
android:id="#+id/navigation_account"
android:icon="#drawable/ic_person_black_24dp"
android:title="#string/account" />
<!-- Our invisible item -->
<item
android:id="#+id/invisible"
android:visible="false"
android:icon="#drawable/ic_person_black_24dp"
android:title="#string/account" />
</menu>
Notice that I have added that item at last position and given it an id invisible and also set it's visibility to false.
Now, In the activity just set selected item id to this id like this
bottomNavMenu.setSelectedItemId(R.id.invisible);
Thanks

XML Code
<group android:checkableBehavior="single">
<item android:id="#+id/nav_item1" />
<item android:id="#+id/nav_item2" />
<item android:id="#+id/nav_item3" />
<item android:id="#+id/nav_item4" />
<item
android:id="#+id/nav_item5"
android:icon="#drawable/icon_item5"
android:title="Home"
android:visible="false"/>
</group>
JAVA Code
bottomNavigationView.getMenu().getItem(4).setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_item1:
return true;
case R.id.nav_item2:
return true;
case R.id.nav_item3:
return true;
case R.id.nav_item4:
return true;
}
// Default operation you want to perform
return false;
}
});

If anyone interested in a nice Kotlin solution, here's mine:
//disable the preselected first item
//<navigation> is the bottom navigation view
navigation.menu.getItem(0).isCheckable=false
Then in the selection listener, make sure that you'll show the user what he selected
BottomNavigationView.OnNavigationItemSelectedListener { item: MenuItem ->
when (item.itemId) {
R.id.option1 -> {
item.isCheckable=true //here is the magic
//notify the listener
return#OnNavigationItemSelectedListener true
}
R.id.option2 ->{
item.isCheckable=true
//notify the listener
return#OnNavigationItemSelectedListener true
}
R.id.option3 ->{
//go to forgot user fragment
item.isCheckable=true
//notify the listener
return#OnNavigationItemSelectedListener true
}
else -> false
}
}
Finally , make a selector color so you can change easily in color
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:color="#color/colorAccent" />
<item android:color="#color/colorPrimary" />
And add the selector to the navigation view
app:itemIconTint="#color/navigation_colors"
app:itemTextColor="#color/navigation_colors"
Now, if you need to change the colours, just change the selector.

Add this line in your onCreate method
mBottomNavigation.setSelectedItemId("ID OF YOUR MENU ITEM");

Use setCheckable instead of setChecked(false) in line:
mBottomNavigation.getMenu().getItem(0).setCheckable(false);
It works for me.

I've created a sample project and by default there is no checked item. Just make sure you don't have any navigationView.setCheckedItem(R.id.id) on your code.

My solution was to select a different tab and immediately after select the tab I initially wanted.
bottomNavigationView.selectedItemId = R.id.dummy_tab
bottomNavigationView.selectedItemId = R.id.tab_to_select
The setOnItemReselectedListener disables reselect tab selections, but the navigationView has a default tab selected and don't render after creation because is invoking setOnItemReselectedListener
Tried the invisible solution but didn't work with programmatically bottomMenu creation.

Old question, but if you still facing issue - just use this:
bottomNavigationView.getMenu().getItem(0).setCheckable(false);
And it:
bottomNavigationView.setOnItemReselectedListener(new NavigationBarView.OnItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.navigation_home) {
item.setCheckable(true);
}
}
});

I combined the solution mentioned by #Ashish Kumar and resolved my query and
private void customizeBottomBar() {
mBottomNavigation.getMenu().getItem(0)
.setIcon(ContextCompat.getDrawable(activity, R.drawable.ic_reserve_normal));
changeMenuItemCheckedStateColor(mBottomNavigation, getUnCheckedColor(), getUnCheckedColor());
}
/**
* Method to change the color state of bottom bar view
* #param bottomNavigationView - BottomNavigation view instance
* #param checkedColorHex int value of checked color code
* #param uncheckedColorHex int value of unchecked color code
*/
void changeMenuItemCheckedStateColor(BottomNavigationView bottomNavigationView,
int checkedColorHex, int uncheckedColorHex) {
int[][] states = new int[][]{
new int[]{-android.R.attr.state_checked}, // unchecked
new int[]{android.R.attr.state_checked}, // checked
};
int[] colors = new int[]{
uncheckedColorHex,
checkedColorHex
};
ColorStateList colorStateList = new ColorStateList(states, colors);
bottomNavigationView.setItemTextColor(colorStateList);
bottomNavigationView.setItemIconTintList(colorStateList);
}

Related

BottomNavigationView - How to uncheck all MenuItems and keep Titles being displayed?

As I liked the design from BottomNavigationView I decided to implement a new Menu for my App with it, instead of just using simple buttons.
I took this post as a guideline.
According to BottomNavigationView's documentation, its purpose is to
provide quick navigation between top-level views of an app. It is
primarily designed for use on mobile.
In my case, I just want each MenuItem to launch an activity, but by default there is always one MenuItem selected:
I tried to set the color to white with:
app:itemIconTint="#color/white"
app:itemTextColor="#color/white"
Still, visibly selected MenuItem is different from others (Title size bigger), which is still bothering me:
I came with the idea to place a hidden MenuItem to select like:
<item
android:id="#+id/uncheckedItem"
android:title="" />
and make its view GONE:
bottomNavigationView.getMenu().findItem(R.id.uncheckedItem).setChecked(true);
bottomNavigationView.findViewById(R.id.uncheckedItem).setVisibility(View.GONE);
This makes all MenuItems unchecked, but by default BottomNavigationView is hidding Titles, as it has more than 3 MenuItems to display, even if the fourth MenuItem is settle to GONE:
So my question remains, is there away/hack to unselect all MenuItems and keep its titles being displayed?
mNavigationBottom.getMenu().setGroupCheckable(0, false, true);
To unselect all items I have create this extension:
fun BottomNavigationView.uncheckAllItems() {
menu.setGroupCheckable(0, true, false)
for (i in 0 until menu.size()) {
menu.getItem(i).isChecked = false
}
menu.setGroupCheckable(0, true, true)
}
menu.setGroupCheckable(0, true, false) make it possible.
The third parameter made the menu not exclusive and then within the loop you change the checked status.
To finish set the menu to exclusive again.
Here the doc
Thanks for your idea. I have implement it in my lib.
I have a better way do it by reflect. So it won't show space.
If you have interest. Click here : https://github.com/ittianyu/BottomNavigationViewEx
private void initBottomViewAndLoadFragments(final BottomNavigationViewEx bnve) {
bnve.enableAnimation(false);
bnve.enableShiftingMode(false);
bnve.enableItemShiftingMode(false);
// use the unchecked color for first item
bnve.setIconTintList(0, getResources().getColorStateList(R.color.bnv_unchecked_black));
bnve.setTextTintList(0, getResources().getColorStateList(R.color.bnv_unchecked_black));
bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
private boolean firstClick = true;
private int lastItemId = -1;
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// restore the color when click
if (firstClick) {
firstClick = false;
bnve.setIconTintList(0, getResources().getColorStateList(R.color.selector_bnv));
bnve.setTextTintList(0, getResources().getColorStateList(R.color.selector_bnv));
}
if (firstClick || lastItemId == -1 || lastItemId != item.getItemId()) {
lastItemId = item.getItemId();
} else {
return false;
}
// do stuff
return fillContent(item.getItemId());
}
});
}
-- res/color/selector_bnv.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/bnv_checked_white" android:state_checked="true" />
<item android:color="#color/bnv_unchecked_black" />
</selector>
-- res/values/colors.xml
<color name="bnv_checked_white">#android:color/white</color>
<color name="bnv_unchecked_black">#android:color/black</color>
Your solution seems change the space between items
There is my solution :
"Just set color of clicked same as color of un-clicked."
for example:
private void changeMenuItemCheckedStateColor(BottomNavigationView bottomNavigationView, String checkedColorHex, String uncheckedColorHex) {
int checkedColor = Color.parseColor(checkedColorHex);
int uncheckedColor = Color.parseColor(uncheckedColorHex);
int[][] states = new int[][] {
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] {android.R.attr.state_checked}, // checked
};
int[] colors = new int[] {
uncheckedColor,
checkedColor
};
ColorStateList colorStateList = new ColorStateList(states, colors);
bottomNavigationView.setItemTextColor(colorStateList);
bottomNavigationView.setItemIconTintList(colorStateList);
}
if you want to un-check all items, you can
changeMenuItemCheckedStateColor(mBottomNavigationView, "#999999", "#999999");
if you want to restore the color setting, you can
changeMenuItemCheckedStateColor(mBottomNavigationView, "FF743A", "999999");
I found my own solution merging my progress with this post.
Steps:
Update proguard-rules.pro and sync build
Create Helper to disable BottomNavigationView Shift Mode
Create an Item to hide on Menu.xml
Inflate BottomNavigationView
Set Item to be hidden as Checked GONE
Use Helper to disable Shifting Mode
Output:
Working code:
proguard-rules.pro:
-keepclassmembers class android.support.design.internal.BottomNavigationMenuView {
boolean mShiftingMode;
}
BottomNavigationShiftHelper.java:
public class BottomNavigationShiftHelper {
private final static String TAG = "DEBUG_BOTTOM_NAV_UTIL";
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
item.setShiftingMode(false);
// set once again checked value, so view will be updated
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.d(TAG, "Unable to get shift mode field");
} catch (IllegalAccessException e) {
Log.d(TAG, "Unable to change value of shift mode");
}
}
}
Activity Sample.java:
private void loadNavigationBar() {
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation_bar);
bottomNavigationView.getMenu().findItem(R.id.uncheckedItem).setChecked(true);
bottomNavigationView.findViewById(R.id.uncheckedItem).setVisibility(View.GONE);
BottomNavigationViewUtils.disableShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.newList:
//Do The Math
break;
case R.id.loadList:
//Do The Math
break;
case R.id.settings:
//Do The Math
break;
}
return false;
}
});
}
BottomNavigationMenu.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/newList"
android:enabled="true"
android:icon="#drawable/new_list"
android:title="#string/common.button.list.new"
app:showAsAction="withText" />
<item
android:id="#+id/loadList"
android:enabled="true"
android:icon="#drawable/load"
android:title="#string/common.button.list.load"
app:showAsAction="withText" />
<item
android:id="#+id/settings"
android:enabled="true"
android:icon="#drawable/settings"
android:title="#string/common.label.settings"
app:showAsAction="withText" />
<item
android:id="#+id/uncheckedItem"
android:title="" />
</menu>
BottomNavigationComponent (inside Activity.xml):
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:itemIconTint="#color/white"
app:itemTextColor="#color/white"
android:background="#drawable/BottomNavigationMenu.xml"
app:menu="#menu/supercart_bottom_navigation" />
Try this, it worked for me
<item
android:id="#+id/uncheckedItem"
android:visible="false"
android:title="" />
and set
bottomNavigationView.getMenu().findItem(R.id.uncheckedItem).setChecked(true);
you get all menu item view as unselected; since the selection is given for uncheckedItem which is invisible
Hope it helped you.
There is an exception in accepted answer which we set maximum item we cant implement that code.So I got a code that is more simple than accepted code and it's also working with maximum item.
I referred from here Custom TextSize of BottomNavigationView support android
In your dimen.xml you can put:
<dimen name="design_bottom_navigation_text_size" tools:override="true">10sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">10sp</dimen>
Doing this you are overriding the default value of dimen that the internal classes of BottomNavigationView use. So be carreful.
Set this code in your onCreate method where the bottom navigation view initialized
mNavigationBottom.getMenu().setGroupCheckable(0, false, true);
and Last set your bottom navigation bar like this :
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
android:fitsSystemWindows="true"
app:labelVisibilityMode="labeled"
app:layout_anchorGravity="fill"
app:menu="#menu/bottom_nav_menu" />
In this set your app:labelVisibilityMode to labeled
This is the same as the accepted answer except I have changed two lines of code marked below. When looping through the BottomNavigationItemViews, I set checked to false always and I also set checkable to false. This prevents the Menu Items from changing size. You still need this proguard rule:
-keepclassmembers class android.support.design.internal.BottomNavigationMenuView {
boolean mShiftingMode;
}
Updated code:
static void removeShiftMode(BottomNavigationView view)
{
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try
{
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++)
{
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
item.setShiftingMode(false);
item.setChecked(false); // <--- This line changed
item.setCheckable(false); // <-- This line was added
}
}
catch (NoSuchFieldException e)
{
Log.e("ERROR NO SUCH FIELD", "Unable to get shift mode field");
}
catch (IllegalAccessException e)
{
Log.e("ERROR ILLEGAL ALG", "Unable to change value of shift mode");
}
}
The best answer mNavigationBottom.getMenu().setGroupCheckable(0, false, true) did not work for me. It still showed the first item as being selected.
What did work for me is to have an invisible item and to select that, exactly like you did in the question.
Add app:labelVisibilityMode="labeled" to your BottomNavigationView so that all items remain in view with their titles.
if(isDarkMode(context)) {
mBotNavView.setItemIconTintList(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
} else {
mBotNavView.setItemIconTintList(ColorStateList.valueOf(Color.parseColor("#000000")));
}
public boolean isDarkMode(Context context) {
int nightModeFlags = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
return darkMode = (nightModeFlags == Configuration.UI_MODE_NIGHT_YES);
}

How to uncheck checked items in Navigation View?

I know it's possible to highlight a navigation view item by calling setCheckedItem() or return true value in onNavigationItemSelected to display the item as the selected item, but How can I uncheck the checked items of a navigation view?
This will uncheck the items:
int size = mNavigationView.getMenu().size();
for (int i = 0; i < size; i++) {
mNavigationView.getMenu().getItem(i).setCheckable(false);
}
I saw #arsent solution and gave it a try, and it will indeed do what you want, which is to unselect all the items... but, I was having an issue in the following scenario:
Select menu item 1 (using NavigationView#setCheckedItem)
Unselect all the items as per #arsent's solution
Select menu item 1 again (using NavigationView#setCheckedItem)
In this scenario, item 1 will not be marked as checked. That's because internally the navigation view keeps track of the previously selected item set in step 1, which doesn't change in step 2, and it just skips step 3 because the previously selected item is the same as the one we're selecting now.
My suggestion (and an alternative solution) to avoid this is just having a dummy invisible item and use NavigationView#setCheckedItem to select that item whenever you want to unselect all, like so
<item
android:id="#+id/menu_none"
android:title=""
android:visible="false"/>
To unselect all just do
mNavigationView.setCheckedItem(R.id.menu_none);
To uncheck all MenuItems including SubMenu items you have to use recursion -
private void unCheckAllMenuItems(#NonNull final Menu menu) {
int size = menu.size();
for (int i = 0; i < size; i++) {
final MenuItem item = menu.getItem(i);
if(item.hasSubMenu()) {
// Un check sub menu items
unCheckAllMenuItems(item.getSubMenu());
} else {
item.setChecked(false);
}
}
}
Call above method for unchecking all items, like below -
unCheckAllMenuItems(navigationView.getMenu());
just make your items non checkable like so
<item
android:id="#+id/profile_item"
android:checkable="false"
android:title="#string/profile"/>
Quoting #Codeversed, there is "no need to loop menu items with added overhead!". But, there is no need to create multiple groups (in this case he is creating the #+id/grp1 and #+id/grp2) to uncheck a previous checked item.
You can simple add a single group for all elements with the android:checkableBehavior, like this:
<group android:checkableBehavior="single">
<item
android:id="#+id/id1"
android:checked="true"
android:icon="#drawable/drawable1"
android:title="#string/string1" />
<item
android:id="#+id/id2"
android:icon="#drawable/drawable2"
android:title="#string/string2" />
</group>
Joao's solutions didn't not work for me as totally expected. This would lead to a blank space from unchecked Item View on my Navigation.
Just make sure to set the view as gone:
<item
android:id="#+id/your_menu_item_id_to_hide"
android:title=""
android:visible="false"/>
bottomNavigationView.getMenu().findItem(R.id.your_menu_item_id_to_hide).setChecked(true);
bottomNavigationView.findViewById(R.id.your_menu_item_id_to_hide).setVisibility(View.GONE);
Arsent solution is not necessary in this case.
All you need to do is surround your groups like this:
<group>
<group
android:id="#+id/grp1">
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_account_circle_24dp"
android:title="#string/profile" />
</group>
<group
android:id="#+id/grp2">
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_24dp"
android:title="#string/settings" />
<item
android:id="#+id/nav_help"
android:icon="#drawable/topic_help"
android:title="#string/help_feedback" />
</group>
</group>
No need to loop menu items with added overhead!
I guess someone like me use those methods just like this
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_today:
break;
case R.id.nav_calendar:
navigationView.getMenu().performIdentifierAction(R.id.nav_today, 0);
navigationView.getMenu().getItem(0).setChecked(true);//or
navigationView.setCheckedItem(R.id.nav_today);//or
drawerLayout.closeDrawers();
break;
}
return true;
}
Trying to check R.id.nav_today after you clicked on R.id.nav_calendar, (btw: checkableBehavior="single"), unfortunately it will not work.
That is because after your code navigationView.setCheckedItem(R.id.nav_today) be called then the R.id.nav_today will be checked immediately, but after this, your click on R.id.nav_calendar will check itself.
That is why whatever methods you use seem never work at all. It is work, but be override immediately.
To uncheck it inside NavigationItemSelectedListener I had to use post (to UI thread):
App.getHandler().post(() -> menuItem.setChecked(false));
Full example:
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
menuItem -> {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
...
}
App.getHandler().post(() -> menuItem.setChecked(false));
return true;
});
p.s. in my case App.getHandler() returns Handler instance for UI Thread Lopper
I had to use a combination of all the solutions mentioned here. In my case, I want to open an URL Intent when the Item is clicked (open a Browser). The clicked item should get unchecked after the click and reset to the item before. Important is to understand, that you cannot uncheck an item during the click listener event, since the checked state will be handled afterwards. So this is my solution in Kotlin:
val item = navigationView.menu.findItem(R.id.menu_item)
item.setOnMenuItemClickListener {
val oldItem = navigationView.checkedItem
rootView.postDelayed({ // you can use here any View to post a Runnable with a delay
navigationView.setCheckedItem(oldItem?.itemId ?: R.id.default_item)
}, 500)
browseURL("https://www.example.com")
true
}
I use a Navigation Drawer in combination with the Jetpack Navigation.
i combine #arsent and #Rahul answers and write this code:
private void NavigationView_NavigationItemSelected(object sender, NavigationView.NavigationItemSelectedEventArgs e)
{
var size = navigationView.Menu.Size();
for (int i = 0; i < size; i++)
{
var item= navigationView.Menu.GetItem(i).SetChecked(false);
if (item.HasSubMenu)
{
for (int j = 0; j < item.SubMenu.Size(); j++)
{
item.SubMenu.GetItem(j).SetChecked(false);
}
}
}
e.MenuItem.SetChecked(true);
drawerLayout.CloseDrawers();
}
above code is for xamarin c# and work,but u can easily convert to java
#arsent's answer is correct but setCheckable(false) uncheck all items, it prevents the items from being checked in the future.
Just use setChecked(false)
int size = mNavigationView.getMenu().size();
for (int i = 0; i < size; i++) {
mNavigationView.getMenu().getItem(i).setChecked(false);
}

Use a ColorStateList with a checkable option menu item and state_checked

My options menu is populated with items such as:
<item
android:id="#+id/menu_bus"
android:checkable="true"
android:checked="true"
android:icon="#drawable/icon_bus"
android:title="#string/bus"
app:showAsAction="ifRoom"/>
Here's my onOptionsItemsSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
item.setChecked(!item.isChecked());
Log.d("test", "Item " + item + " is now checked: " + item.isChecked());
ColorStateList colorStateList = getResources().getColorStateList(R.color.options_menu_colors);
Drawable d = DrawableCompat.wrap(item.getIcon());
DrawableCompat.setTintList(d, colorStateList);
item.setIcon(d);
return true;
}
As you can see my goal is to have widget tinting in older versions of android, using the feature of the support libraries v22.1.
The color is defined as such:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/accent" android:state_checked="true"/>
<item android:color="#color/secondary_text"/>
</selector>
However the state_checked isn't working with checkbox menu items!
Here's the log of icon presses:
D/test (11529): Item Bus is checked: false
D/test (11529): Item Bus is checked: true
D/test (11529): Item Bus is checked: false
D/test (11529): Item Bus is checked: true
I tried to switch the selector to state_pressed: this one works! While touching the menu item, the color changes!
So why can't the ColorStateList work with the state_checked on option menu items?
PS: using this works:
int colorId = item.isChecked() ? R.color.accent : R.color.secondary_text;
int color = getResources().getColor(colorId);
DrawableCompat.setTint(d, color);
But obviously I would've wanted something more elegant.
According to the documentation Using checkable menu items,
you have to manually indicate the checked state, for e.g.
if(item.isCheckable()) {
int[] state = {item.isChecked() ? android.R.attr.state_checked : android.R.attr.state_empty};
item.getIcon().setState(state);
}
It likely doesn't work because your Drawable doesn't implement the Checkable interface - the MenuItem is what's checked.

Refresh menu item animation in ActionBarSherlock

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
return true;
case R.id.searchIcon:
return true;
case R.id.startRefresh:
refreshItem = item;
refresh();
return true;
case R.id.stopRefresh:
if (refreshItem != null && refreshItem.getActionView() != null) {
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void refresh() {
if (FeedActivity.this != null) {
/*
* Attach a rotating ImageView to the refresh item as an ActionView
*/
LayoutInflater inflater = (LayoutInflater) FeedActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView) inflater.inflate(
R.layout.refresh_action_view, null);
Animation rotation = AnimationUtils.loadAnimation(
FeedActivity.this, R.anim.clockwise_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
refreshItem.setActionView(iv);
}
}
Before Clicking:
After Clicking:
Here the icon is being animated(rotating).
Problem:
why is it shifting to the left?
once it shifts to the left, the icon becomes non clickable and strangely the device back button also doesn't work
EDIT:
In comments below this answer:
Animated Icon for ActionItem
Jake Warton says if you are using a square and correct sized icon for the menu item, you wont get this weird behaviour, to someone who has the same problem.
But i am using a 32x32 image on a device which uses mdpi drawables. Which as stated there must work :(
Thank You
EDIT:
refresh_action_view.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/Widget.Sherlock.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_refresh" />
Custom Style i use in my app
<style name="My_solid_ActionBar" parent="#style/Widget.Sherlock.Light.ActionBar.Solid.Inverse">
<item name="background">#drawable/ab_solid_My</item>
<item name="backgroundStacked">#drawable/ab_stacked_solid_My</item>
<item name="backgroundSplit">#drawable/ab_bottom_solid_My</item>
<item name="progressBarStyle">#style/My_ProgressBar</item>
<item name="android:background">#drawable/ab_solid_My</item>
<item name="android:backgroundStacked">#drawable/ab_stacked_solid_My</item>
<item name="android:backgroundSplit">#drawable/ab_bottom_solid_My</item>
<item name="android:progressBarStyle">#style/My_ProgressBar</item>
</style>
The issue is that you're not handling all menu inflation in onCreateOptionsMenu(). The basic logic for an ActionBar refresh animation I've seen used in apps with open source , for example Andlytics (and also used myself in projects), is to implement a boolean flag in onCreateOptionsMenu() to decide whether to show the refresh animation.
You can implement it like this: When your refresh() method is called, it sets the boolean isRefreshing flag to true and calls inValidateOptionsMenu() which 'behind the scene' calls onCreateOptionsMenu() to start the animation:
Inflate the menu in onCreateOptionsMenu(...):
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
//inflate a menu which shows the non-animated refresh icon
inflater.inflate(R.menu.my_ab_menu, menu);
if (isRefreshing) {
//if we're refreshing, show the animation
MenuItem item = menu.findItem(R.id.refreshMenuItem);
item.setActionView(R.layout.action_bar_indeterminate_progress);
ImageView iv = (ImageView) item.getActionView().findViewById(R.id.loadingImageView);
((AnimationDrawable) iv.getDrawable()).start();
}
}
Start animation like so:
public void refresh(){
isRefreshing = true;
inValidateOptionsMenu();
}
If you want the user to start the animation when he taps the refresh icon, do like this in onOptionsItemSelected():
case R.id.refreshMenuItem:
isRefreshing = true;
item.setActionView(R.layout.action_bar_indeterminate_progress);
ImageView iv = (ImageView) item.getActionView().findViewById(R.id.loadingImageView);
((AnimationDrawable) iv.getDrawable()).start();
//...
To stop the animation call:
isRefreshing = false;
invalidateOptionsMenu();
This code is from a Fragment so you may have to tweak if for an Activity, but I think it communicates the basic idea.
I tried the exact same code you use and it works just fine for me. The only things that might be different are two things:
1) the refresh_action_view layout (here's mine for comparison):
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
style="?attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_menu_refresh" />
2) The display options of your action bar (here's my styles.xml for comparison).
<resources>
<style name="AppTheme" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="android:actionBarStyle">#style/Widget.ActionBar</item>
<item name="actionBarStyle">#style/Widget.ActionBar</item>
</style>
<style name="Widget.ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid.Inverse">
<item name="android:displayOptions">showHome|useLogo|showCustom</item>
<item name="displayOptions">showHome|useLogo|showCustom</item>
</style>
</resources>
Can you share yours as well?

How to change the default icon on the SearchView, to be use in the action bar on Android?

I'm having a bit of trouble customizing the search icon in the SearchView. On my point of view, the icon can be changed in the Item attributes, right? Just check the code bellow..
Can someone tell me what I'm doing wrong?
This is the menu I'm using, with my custom search icon icn_lupa. But when I run the app, I always get the default search icon...
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_search"
android:title="#string/menu_search"
android:icon="#drawable/icn_lupa"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
I've found another way to change the search icon which goes in the same line as Diego Pino's answer but straight in onPrepareOptionsMenu.
In your menu.xml (same as before)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_fav"
android:title="#string/action_websearch"
android:showAsAction="always|never"
android:actionViewClass="android.widget.SearchView" />
</menu>
In your activity:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem searchViewMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchViewMenuItem.getActionView();
int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
ImageView v = (ImageView) mSearchView.findViewById(searchImgId);
v.setImageResource(R.drawable.your_new_icon);
mSearchView.setOnQueryTextListener(this);
return super.onPrepareOptionsMenu(menu);
}
I followed the example for changing the edittext in this example.
You should be able to do this for all icons/backgrounds in your SearchView, to find the right ID you can check here.
UPDATE November 2017:
Since this answer android has been updated with the possibility of changing the search icon through the XML.
If you target anything below android v21 you can use:
<android.support.v7.widget.SearchView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:searchIcon="#drawable/ic_search_white_24dp"
app:closeIcon="#drawable/ic_clear_white_24dp" />
Or v21 and later:
<SearchView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:searchIcon="#drawable/ic_search_white_24dp"
android:closeIcon="#drawable/ic_clear_white_24dp" />
And there are even more options:
closeIcon
commitIcon
goIcon
searchHintIcon
searchIcon
voiceIcon
Nice answer from #just_user
For my case, since I am using the appcompat v7 library for the SearchView + ActionBar, i modified his solution a bit to make it compatible to my project, it should work so as long as you did not modify anything when you added appcompat v7 as library
XML:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:metrodeal="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/main_menu_action_search"
android:orderInCategory="100"
android:title="#string/search"
metrodeal:showAsAction="always"
metrodeal:actionViewClass="android.support.v7.widget.SearchView"
android:icon="#drawable/search_btn"/>
</menu>
Java code:
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem searchViewMenuItem = menu.findItem(R.id.main_menu_action_search);
SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchViewMenuItem);
int searchImgId = android.support.v7.appcompat.R.id.search_button; // I used the explicit layout ID of searchview's ImageView
ImageView v = (ImageView) mSearchView.findViewById(searchImgId);
v.setImageResource(R.drawable.search_btn);
super.onPrepareOptionsMenu(menu);
}
Excuse for the very big icon (I have not resized the icon just yet), but it should work as it is.
I was struggling with this too but then I accidentaly used 'collapseActionView' and that fixed it!
My menu.xml looks like this now:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_search"
android:title="#string/menu_search"
android:showAsAction="always|withText|collapseActionView"
android:actionViewClass="android.widget.SearchView"
android:icon="#android:drawable/ic_menu_search" />
</menu>
The downside of this is that on tablets the SearchView will appear on the left side of the ActionBar instead of where the searchicon is, but I don't mind that.
I defined a style to do it .
here is my xml:
<android.support.v7.widget.SearchView
android:id="#+id/sv_search"
android:icon="#android:drawable/ic_menu_search"
android:layout_width="fill_parent"
**style="#style/CitySearchView"**
android:layout_height="wrap_content"/>
and this is my style:
<style name="CitySearchView" parent="Base.Widget.AppCompat.SearchView">
<item name="searchIcon">#drawable/ic_more_search</item>
</style>
That it!
After finish that,just take a look at Base.Widget.AppCompat.SearchView.
<style name="Base.Widget.AppCompat.SearchView" parent="android:Widget">
<item name="layout">#layout/abc_search_view</item>
<item name="queryBackground">#drawable/abc_textfield_search_material</item>
<item name="submitBackground">#drawable/abc_textfield_search_material</item>
<item name="closeIcon">#drawable/abc_ic_clear_mtrl_alpha</item>
<item name="searchIcon">#drawable/abc_ic_search_api_mtrl_alpha</item>
<item name="goIcon">#drawable/abc_ic_go_search_api_mtrl_alpha</item>
<item name="voiceIcon">#drawable/abc_ic_voice_search_api_mtrl_alpha</item>
<item name="commitIcon">#drawable/abc_ic_commit_search_api_mtrl_alpha</item>
<item name="suggestionRowLayout">#layout/abc_search_dropdown_item_icons_2line</item>
</style>
every item can be override by define a new style .
Hope it helps!
There's a way to do this. The trick is to recover the ImageView using its identifier and setting a new image with setImageResource(). This solution is inspired on Changing the background drawable of the searchview widget.
private SearchView searchbox;
private void customizeSearchbox() {
setSearchHintIcon(R.drawable.new_search_icon);
}
private void setSearchHintIcon(int resourceId) {
ImageView searchHintIcon = (ImageView) findViewById(searchbox,
"android:id/search_mag_icon");
searchHintIcon.setImageResource(resourceId);
}
private View findViewById(View v, String id) {
return v.findViewById(v.getContext().getResources().
getIdentifier(id, null, null));
}
SearchView searchView = (SearchView) findViewById(R.id.address_search);
try {
Field searchField = SearchView.class
.getDeclaredField("mSearchButton");
searchField.setAccessible(true);
ImageView searchBtn = (ImageView) searchField.get(searchView);
searchBtn.setImageResource(R.drawable.search_glass);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
After some research I found the solution here. The trick is that the icon is not in an ImageView but in the Spannable object.
// Accessing the SearchAutoComplete
int queryTextViewId = getResources().getIdentifier("android:id/search_src_text", null, null);
View autoComplete = searchView.findViewById(queryTextViewId);
Class<?> clazz = Class.forName("android.widget.SearchView$SearchAutoComplete");
SpannableStringBuilder stopHint = new SpannableStringBuilder(" ");
stopHint.append(getString(R.string.your_new_text));
// Add the icon as an spannable
Drawable searchIcon = getResources().getDrawable(R.drawable.ic_action_search);
Method textSizeMethod = clazz.getMethod("getTextSize");
Float rawTextSize = (Float)textSizeMethod.invoke(autoComplete);
int textSize = (int) (rawTextSize * 1.25);
searchIcon.setBounds(0, 0, textSize, textSize);
stopHint.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set the new hint text
Method setHintMethod = clazz.getMethod("setHint", CharSequence.class);
setHintMethod.invoke(autoComplete, stopHint);
In menu xml:
<item
android:id="#+id/menu_filter"
android:actionLayout="#layout/menu_filter"
android:icon="#drawable/ic_menu_filter"
android:orderInCategory="10"
android:showAsAction="always"
android:title="#string/menu_filter"/>
and create the layout/menu_filter:
<?xml version="1.0" encoding="utf-8"?>
<SearchView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:searchIcon="#drawable/ic_menu_filter"/>
then in activity's onCreateOptionsMenu or onPrepareOptionsMenu:
SearchView searchView = (SearchView) menu.findItem(R.id.menu_filter).getActionView();
searchView.setOnQueryTextListener(this);
It looks like the actionViewClass overides the icon and it doesn't look like you can change it from this class.
You got two solutions:
Live with it and I think it's the best option in terms of user experience and platform conformity.
Define your own actionViewClass
<SearchView
android:searchIcon="#drawable/ic_action_search"
..../>
use the searchIcon xml tag
This works with Material Design (MaterialComponents theme) and BottomAppBar.
If you are using androidx library, for example:
<item
android:id="#+id/sv"
android:title="#string/search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="always" />
You can create a method and invoke it from wherever you want:
/**
* Set SearchView Icon
* #param i Drawable icon
*/
private void setSVIcon(int i) {
ImageView iv = searchView.findViewById(androidx.appcompat.R.id.search_button);
iv.setImageDrawable(ResourcesCompat.getDrawable(getResources(), i, null));
}
Usage example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(m, menu);
MenuItem mn = menu.findItem(R.id.sv);
if (mn != null) {
searchview = (SearchView) mn.getActionView();
setSVIcon(R.drawable.ic_sr);
}
}
Update hint of AutocompleteTextView for updating search icon in the expanded mode, copied from android source,
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) mSearchMenuItem.getActionView();
int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
ImageView v = (ImageView) searchView.findViewById(searchImgId);
v.setImageResource(R.drawable.search_or);
int searchTextViewId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(searchTextViewId);
searchTextView.setHintTextColor(getResources().getColor(R.color.hint_color_white));
searchTextView.setTextColor(getResources().getColor(android.R.color.white));
searchTextView.setTextSize(18.0f);
SpannableStringBuilder ssb = new SpannableStringBuilder(" "); // for the icon
ssb.append(hintText);
Drawable searchIcon = getResources().getDrawable(R.drawable.search_or);
int textSize = (int) (searchTextView.getTextSize() * 1.25);
searchIcon.setBounds(0, 0, textSize, textSize);
ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
searchTextView.setHint(ssb);
return super.onPrepareOptionsMenu(menu);
}
From API 21 you can change it in xml:
android:searchIcon="#drawable/loupe"
android:closeIcon="#drawable/x_white"
for api level < 21, i did this:
int searchImgId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
ImageView ivIcon = (ImageView) searchView.findViewById(searchImgId);
if(ivIcon!=null)
ivIcon.setImageResource(R.drawable.ic_search);
from this
to this
There are three magnifying glass icons. two of them are shown when IconizedByDefault is true(one which is shown before pressing and one is shown in the "hint") and one is shown all the time when IconizedByDefault is false. all the fields are private so the way to get them is by their xml id. (most of the code is mentioned separately in other answers in this post already)
when IconizedByDefault is true change the icon in the hint (which is seen only after pressing the icon) by :
mSearchSrcTextView = (SearchAutoComplete)findViewById(R.id.search_src_text);
then do the same as in the android source code:
final int textSize = (int) (mSearchSrcTextView.getTextSize() * 1.25);
newSearchIconDrawable.setBounds(0, 0, textSize, textSize);
final SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.setSpan(new ImageSpan(newSearchIconDrawable), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(hintText);
mSearchHintIcon was replaced with newSearchIconDrawable which is your new search icon.
Then set the hint with
mSearchSrcTextView.setHint(ssb);
The other 2 icons are in an ImageView, which can be found by their Id.
for the icon when searchview is closed (when iconizedByDefault is true) do:
mSearchButton = (ImageView) findViewById(R.id.search_button);
and for the one that always appears (if iconizedByDefault is false)
mCollapsedIcon = (ImageView) findViewById(R.id.search_mag_icon);
Desperate solution using Kotlin
val s = (searchView.getAllChildren().firstOrNull() as? LinearLayout)?.getAllChildren()?.filter { it is AppCompatImageView }?.firstOrNull() as? AppCompatImageView
s?.setImageResource(R.drawable.search)
getAllChildren:
fun ViewGroup.getAllChildren() : ArrayList<View> {
val views = ArrayList<View>()
for (i in 0..(childCount-1)) {
views.add(getChildAt(i))
}
return views
}
Hope it helps someone.
My solution:
Use two menu xml files. In one of the xmls the menu item has an actionView and in the other one no. Initially inflate the collapsed menu and when the menu item is clicked, invalidate the menu and inflate the expanded menu xml and make sure you call setIconified(false);
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
if(!mShowSearchView)
{
inflater.inflate(R.menu.menu_collapsed, menu);
}
else
{
inflater.inflate(R.menu.menu_expanded, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setIconified(false);
searchView.setOnCloseListener(new OnCloseListener()
{
#Override
public boolean onClose()
{
mShowSearchView = false;
ActivityCompat.invalidateOptionsMenu(getActivity());
return false;
}
});
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.action_filter)
{
menu.showMenu();
}
else if (item.getItemId() == R.id.action_search)
{
mShowSearchView = true;
ActivityCompat.invalidateOptionsMenu(getActivity());
}
return super.onOptionsItemSelected(item);
}
Just name your icon the same name as the icon that is used by the search view. When it compiles it takes the resource in the project over the icon in the library.
I use the AppCompat library. Yes, specifying android:icon="#drawable/search_icon_png" doesnt work.
So i looked into the source code of #style/Theme.AppCompat and found the icon that android uses.
<item name="searchViewSearchIcon">#drawable/abc_ic_search</item>
So if you rename your search icon inside your drawables to abc_ic_search.png, this icon is rendered as its found in your app drawable first, rather than the appcompat drawable folder.
Works for me :)
Using this approach you can customize the close and clear icons for the search widget as well.

Categories

Resources