Searchview text color android

Change TextColor in SearchView using Android Toolbar

I have the following problem. I’ve setup my Actionbar to use a Toolbar instead using the API 21 with the appcompat-v7:21. The textColorPrimary style tag is configured to use the color @android:color/white , so all the titles in the new Android Toolbar will have a white text color (so far so good).

Now I´ve added a SearchView, and setup a custom background to it like this:

The drawable @drawable/search_background is a plain white rectangle. So guess what? As the title text color in the Toolbar is white, now the text color in the SearchView is white as well, and as the SearchView background is a white rectangle, the user can’t see what he’s typing.

My Question is: How can I have different text colors for the Android Toolbar Title and the SearchView text?

4 Answers 4

After some research I found a secure way to do it.

Digging up in the SearchView styles, I found the layout that is used to display the SearchView. Inside that layout there’s a TextView (the actual field where you type in the SearchView)

Notice the field android:textColor=»?android:attr/textColorPrimary» . This causes the problem I originally had, the text color in the SearchView is the same as the one defined for the Title text color in the Android Toolbar.

Now there’re are several solutions that might work here, but I think that most of those solutions have the same problem. They all rely in the id of the TextView in order to access the view and change the text color, as described here

Personally I think that hardcoding the id of the TextView inside the code is highly risky, because we don’t know if tomorrow Google decides to use another id value for this view, in that case, our code will be broken.

For that reason I’ve created a recursive method that obtains the TextView object in the SearchView, and changes the color to whatever we want.

I’ve tested this code using API 21 with the Toolbar, having the Toolbar Title text color set to white, and setting up the SearchView text color to black and it works perfectly. Also, as we’re accessing the TextView object directly, we can change the hint, drawable, paddings, and everything related to the TextView.

Читайте также:  Что такое rawquery android

Источник

Change color of android.support.v7.widget.SearchView

I am using search view.

Is this possible to change text color and icon color to view?

Currently it shows black text and icon. I want to change it to white color text and white search icon.

6 Answers 6

For the android.support.v7.widget.SearchView you can change the text color, text hint color and the icon with this code :

To Change the Text color :

To Change the close button :

// This excerpt is from Android source code (SearchView.java)

If it resides in toolbar, set theme for toolbar. For example this makes the text(and icon) white

apply this theme to your toolbar hint that (colorControlHighlight) color of ripple effct of your menu items

Yes, you can do it, one of ways to do it:

Not the answer you’re looking for? Browse other questions tagged android android-layout searchview or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Changing action bar searchview hint text color

How can I change the action bar search view hint text colour?

This question explains how to get the EditText when using ABS: Android ActionBar Customize Search View

Is there a android.R.id I could use to get a reference to the EditText so I could change the hint colour? Or is there some other way to change the colour?

18 Answers 18

android:actionBarWidgetTheme of your main theme should point to a style that has a android:textColorHint in it. That one will allow changing the hint text color of the search view.

this worked for me, hope it helps

I resolved it adding this property to the main theme:

And then add the property i want to change in this case the hint color.

Hope it helps 😀

Make sure your application is using theme custom theme as described in enter link description here

A SearchView object extends from LinearLayout , so it holds other views. The trick is to find the view holding the hint text and change the colour programmatically. By traversing the view hierarchy, you can find the widget containing the hint text:

This method works with any theme. Also, you can change the look of other widgets in the SearchView hierarchy, such as the EditText holding the search query.

If you want to change left arrow button in search view, add app:collapseIcon.

Читайте также:  Does android dream electric sheep

If you want to change text color and text hint color, add the following.

If you want to change close icon, add the following.

Just get the textView id of search widget and use setTextColor() method to change the search text color and setHintTextColor() to change the search hints text color.

With the most recent appcompat library (or if you’re targeting 5.0+), this is possible to do purely in XML using a ThemeOverlay :

And then in your layout file:

If you also want it to apply to activities that are using an ActionBar instead of a Toolbar , you can add this to the Activity ‘s theme:

Источник

Change appcompat’s SearchView text and hint color

Does anybody know how to change the text color of the appcompat SearchView? I’ve spent 2 hours and tried several suggestions from SO and none works.

Here is my code:

And in my activity I have this:

8 Answers 8

A SearchView object extends from LinearLayout , so it holds other views. The trick is to find the view holding the hint text and change the colour programmatically. By traversing the view hierarchy, you can find the widget containing the hint text:

This method works with any theme. Also, you can change the look of other widgets in the SearchView hierarchy, such as the EditText holding the search query.

None of the answers worked for me. What eventually worked was setting a theme on the Toolbar and specifying the textColorHint there.

Theme (in styles.xml):

Toolbar (in any layout):

This works because a when you set a theme to a ViewGroup, its attributes also get applied to all child Views of the ViewGroup. This is one of the differences between a theme and a style 🙂

It is possible to customize searchview by using appcompat v7 library.I used appcompat v7 library and defined custom style for it. In drawable folder put bottom_border.xml file which looks like this:

In values folder styles_myactionbartheme.xml:

I defined custommenu.xml file for displaying menu:

Your activity should extend ActionBarActivity instead of Activity. Here is onCreateOptionsMenu method.

In manifest file:

I’ve created kotlin extension functions

Change style of SearchView in Appcompat v21

1) Create a seachable configuration file. This file is traditionally named searchable.xml and must be saved in the res/xml/ project directory.

2) Add metadata and attribute to your activity and action to intent-filter in AndroidManifest.xml

3) Create styles for indicator, icons, hint and text colors.

4) Add Widget.App.Search to BaseAppTheme added in AndroidManifest as activity style

Add ActionBarThemeOverlay to your toolbar initalization

Источник

Можно ли изменить цвет текста в Android SearchView?

Элемент SearchView не имеет свойств для изменения цвета текста. Цвет текста по умолчанию черный и не работает на темном фоне. Есть ли способ изменить цвет текста, не прибегая к хакам?

Читайте также:  Usb dvr камера для android видеорегистратор

Я нашел аналогичный вопрос, связанный с изменением размера текста, но пока на него нет ответов: Как установить SearchView TextSize?

к родительской теме, и это должно изменить введенный текст. Вы также можете использовать

чтобы изменить текст подсказки для SearchView. (Обратите внимание, что вы можете заменить на @android:color/white любое подходящее значение, которое надеетесь использовать)

Попробуйте что-то вроде этого: вы получите дескриптор текстового представления из sdk, а затем измените его, поскольку они не раскрывают его публично.

У меня это работает.

Я хотел сделать нечто подобное. Наконец-то мне пришлось TextView среди SearchView детей найти :

Если вам нужен метод util:

Благодаря @CzarMatt я добавил поддержку AndroidX .

Изменение цвета текста подсказки searchview панели действий дает другое решение. Он работает, но устанавливает только текст и цвет подсказки.

Лучше всего это достигается с помощью нестандартных стилей. Перегрузите стиль виджета панели действий своим собственным стилем. Для голографического освещения с темной панелью действий поместите это в свой собственный файл стилей, например res/values/styles_mytheme.xml :

Убедитесь, что ваше приложение использует настраиваемую тему темы, как описано в описании ссылки здесь.

Вы можете сделать это, установив editTextColor атрибут в стиле.

и вы применяете этот стиль к Toolbar или SearchView в макете.

если вы используете — android.support.v7.widget.SearchView

Вам лучше начать использовать библиотеки поддержки androidx сейчас

Создайте стиль для своего Toolbar

И установите его в качестве темы для Toolbar

Если вы используете android.support.v7.widget.SearchView, это возможно без использования отражения.

Вот как я это делаю в своем приложении:

Они не предоставляют публично идентификаторы для SearchView, отличного от appcompat, но они делают это для AppCompat, если вы знаете, где искать. 🙂

У меня была эта проблема, и это работает для меня.

Если вы основываете тему приложения на голографической теме, вы получите белый текст вместо черного в SearchView.

Я определил файл custommenu.xml для отображения меню:

Ваша активность должна расширять ActionBarActivity вместо Activity. Вот метод onCreateOptionsMenu.

В файле манифеста:

для панели инструментов appcompat-v7 с searchView (предоставляется через MenuItemCompat):

Установка темы панели инструментов на @ style / ThemeOverlay.AppCompat.Light даст темный цвет (черный) для текста подсказки и для введенного текста, но не повлияет на цвет курсора *. Соответственно, установка темы панели инструментов на @ style / ThemeOverlay.AppCompat.Dark даст светлый цвет (белый) для текста подсказки и введенного текста, курсор * в любом случае будет белым.

Настройка вышеуказанных тем:

android: textColorPrimary -> цвет введенного текста

editTextColor -> цвет введенного текста (переопределит влияние android: textColorPrimary, если установлено)

android: textColorHint -> цвет подсказки

* примечание: мне еще предстоит определить, как можно управлять цветом курсора (без использования решения для отражения).

Источник

Оцените статью