I always get that textView is null when doing this:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat
.getActionView(searchItem);
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
}
Anyone know why?
androidx.appcompat.widget.SearchView. A widget that provides a user interface for the user to enter a search query and submit a request to a search provider.
SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class. For making search field visible, SearchView uses setIconifiedByDefault(false) method.
To add a SearchView widget to the app bar, create a file named res/menu/options_menu. xml in your project and add the following code to the file. This code defines how to create the search item, such as the icon to use and the title of the item.
It's a EditText
not a TextView
.
Try something like that:
int id = searchView.getContext()
.getResources()
.getIdentifier("android:id/search_src_text", null, null);
EditText editText = (EditText) searchView.findViewById(id);
Hope it helps.
I'm using action bar of appcompat v7 and my solusion is:
TextView searchText = (TextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
Hope this help.
If you are using AndroidX then you can do like this in kotlin.
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
val searchItem: MenuItem = menu.findItem(R.id.action_search)
val searchView: SearchView = searchItem.actionView as SearchView
val searchText: TextView = searchView?.findViewById(androidx.appcompat.R.id.search_src_text);
searchText.setTextColor(Color.BLACK)
searchText.background = resources.getDrawable(R.drawable.rounded_corner_background)
return true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With