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>
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);
}
}
}
setInputType on a searchView was introduced in API 14. To set it to number try :
searchView.setInputType(InputType.TYPE_CLASS_NUMBER);
This isn't exactly an answer, but keep in mind that the usefulness of input type filters can be contingent on the IME you're using; some keyboards don't readily obey these input types... I learned that the hard way. :(
With that in mind, have you tried using other input types to see if they'll stick? If they do stick, it's likely an IME issue. If they don't, it's likely an issue with the way in which you're trying to enforce the input type.
Now, for a shot at an answer:
You might try, in onCreateOptionsMenu, doing a lookup by ID of that menu item, casting to a SearchView, and setting the input type in code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.default_menu, menu);
if (MyApplication.SUPPORTS_HONEYCOMB) { // quick check for API level
// If we have the honeycomb API, set up the search view
MenuItem searchItem = menu.findItem(R.id.search);
SearchView search = (SearchView) searchItem.getActionView();
// your code here. something like:
search.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
// you also likely want to set up your search listener here.
}
// I'm using ActionBarCompat, in which case
// calling super after populating the menu is necessary here to ensure that the
// action bar helpers have a chance to handle this event.
return super.onCreateOptionsMenu(menu);
}
When using SearchView
from android.support.v7.widget
you can use:
searchView.setInputType(InputType.TYPE_CLASS_NUMBER);