Search code examples
androidandroid-viewandroid-actionbar

How to set a SearchView's input type to numeric


I currently have a SearchView in my app's ActionBar (of which I am populating from an XML layout file) and I am trying to force it to only take numeric input. I've tried setting the android:inputType="number" attribute in XML, but it has no effect.

Does anyone know the source of this problem?

The XML menu resource:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/search"
        android:title="@string/menu_search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@drawable/ic_menu_search_holo_light"
        android:inputType="number" />       
</menu>

Solution

  • If you're setting it in a compatibility library fragment, you need to use SearchViewCompat.setInputType(View searchView, int inputType):

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.searchable, menu);
        MenuItem searchMenuItem = menu.findItem(R.id.action_search);
        if (searchMenuItem != null) {
            SearchView searchView = (SearchView) searchMenuItem.getActionView();
            if (searchView != null) {
                SearchViewCompat.setInputType(searchView, InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
            }
        }
    }