Reputation: 71
Can anyone tell how make Search View hint in centre? Thanks in advance.
Upvotes: 2
Views: 3093
Reputation: 318
If you are using androidx. Use this code
val searchEditText = searchView.findViewById(androidx.appcompat.R.id.search_src_text) as EditText
searchEditText.gravity = Gravity.CENTER
Upvotes: 3
Reputation: 2562
To center the hint and query text use a costume style for your search view :
<style name="AppSearchView" parent="Widget.AppCompat.SearchView" >
<item name="android:textAlignment">center</item>
</style>
and then apply this style to your search view :
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
app:theme="@style/AppSearchView" />
Upvotes: 2
Reputation: 21
I followed Cody's example but I would like to add onto Cody's answer above that it might actually be better to cast the found view to SearchView.SearchAutoComplete (a public static class) instead of EditText, since that's the view directly associated with R.id.search_src_text. This is to avoid any future problems if the Android team decides to swap out the inherited EditText class for another class.
See the associated view here: https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/layout/search_view.xml
Upvotes: 1
Reputation: 4471
For android.support.v7.widget.SearchView
, use the following:
public static void centerHintText(SearchView searchView){
EditText searchEditText = (EditText) searchView.findViewById(R.id.search_src_text);
if (searchEditText != null) {
searchEditText.setGravity(Gravity.CENTER);
}
}
Upvotes: 1
Reputation: 579
To center the hint on the SearchView
you need to center the gravity in the EditText
contained in the SearchView
.
You can find that specific view by using the Layout Inspector in Android Studio (Tools->Android->Layout Inspector). When you click on the search view in your UI, you can see it has a SearchView$SearchAutoComplete
. That's an inner class in the SearchView
which extends AutoCompleteTextView
, which extends EditText
. So, that's the view you want to change. Observe in the property-value pane of the Layout Inspector that the id is id/search_src_text
so you can use that to get the view and center the gravity, like this:
int id = getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchEditText = (EditText) mSearchView.findViewById(id);
if (searchEditText != null) {
searchEditText.setGravity(Gravity.CENTER);
}
Since the id of the EditText
isn't officially documented, there's a null check in there just in case the id changes or isn't consistent everywhere.
Upvotes: 1