Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchView edittext is always null

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?

like image 370
danielrvt-sgb Avatar asked Aug 15 '13 20:08

danielrvt-sgb


People also ask

What is SearchView?

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.

How to implement SearchView?

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.

How to set SearchView in Android Studio?

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.


3 Answers

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.

like image 87
Undisputed Avatar answered Nov 02 '22 23:11

Undisputed


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.

like image 27
Penicylline Avatar answered Nov 02 '22 23:11

Penicylline


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
        }
like image 30
Rajiv Ranjan Avatar answered Nov 03 '22 00:11

Rajiv Ranjan