Skip to content

Instantly share code, notes, and snippets.

@dbachelder
Last active December 11, 2018 21:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbachelder/9587898 to your computer and use it in GitHub Desktop.
Save dbachelder/9587898 to your computer and use it in GitHub Desktop.
style the actionbar compat searchview. inspired by this article: http://nlopez.io/how-to-style-the-actionbar-searchview-programmatically/
final SupportMenuItem searchMenuItem = (SupportMenuItem) menu.findItem(R.id.menu_search);
if (searchMenuItem == null) throw new IllegalArgumentException("menu item is null and that is very suspicious.");
this.searchView = (SearchView) searchMenuItem.getActionView();
if (searchView == null) throw new IllegalArgumentException("search view is null and that is very suspicious.");
searchView.setQueryHint(getActivity().getString(R.string.search_hint));
// wow. much hack. style search box..
Resources resources = searchView.getContext().getResources();
TextView searchBox = (TextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
ImageView closeBtn = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
// create new hint span
SpannableStringBuilder stopHint = new SpannableStringBuilder(" ");
stopHint.append(resources.getString(R.string.search_hint));
// Add the icon as an spannable
Drawable searchIcon = FontIconDrawable.inflate(resources, R.xml.ic_ab_search);
closeBtn.setImageDrawable(FontIconDrawable.inflate(resources, R.xml.ic_ab_close));
Float rawTextSize = searchBox.getTextSize();
int textSize = (int) (rawTextSize * 1.25);
searchIcon.setBounds(0, 0, textSize, textSize);
stopHint.setSpan(new ImageSpan(searchIcon), 1, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set the new hint text
searchBox.setHint(stopHint);
searchBox.setTextColor(Color.WHITE);
searchBox.setHintTextColor(Color.LTGRAY);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment