Можно ли изменить цвет текста на Android SearchView?
Элемент SearchView не имеет свойств для изменения цвета текста. Цвет текста по умолчанию черный и не работает на нашем темном фоне. Есть ли способ изменить цвет текста, не прибегая к хакам?
Я нашел этот похожий вопрос, связанный с изменением размера текста, но до сих пор у него нет ответов:
Как установить SearchView TextSize?
Ответы
Ответ 1
Попробуйте что-то вроде этого:
Вы получите дескриптор текстового представления из sdk, а затем измените его, так как не публикуете его публично.
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
Ответ 2
Добавить
<item name="android:editTextColor">@android:color/white</item>
к родительской теме, и это должно изменить введенный текст. Вы также можете использовать
<item name="android:textColorHint">@android:color/white</item>
чтобы изменить текст подсказки для SearchView. (Обратите внимание, что вы можете заменить @android:color/white
на любое подходящее значение, которое вы надеетесь использовать)
Ответ 3
Это работает для меня.
SearchView searchView = (SearchView) findViewById(R.id.search);
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.white));
searchEditText.setHintTextColor(getResources().getColor(R.color.white));
Ответ 4
Я хотел сделать что-то подобное. Мне наконец-то пришлось найти TextView
среди детей SearchView
:
for (TextView textView : findChildrenByClass(searchView, TextView.class)) {
textView.setTextColor(Color.WHITE);
}
Если вы хотите использовать утилиту:
public static <V extends View> Collection<V> findChildrenByClass(ViewGroup viewGroup, Class<V> clazz) {
return gatherChildrenByClass(viewGroup, clazz, new ArrayList<V>());
}
private static <V extends View> Collection<V> gatherChildrenByClass(ViewGroup viewGroup, Class<V> clazz, Collection<V> childrenFound) {
for (int i = 0; i < viewGroup.getChildCount(); i++)
{
final View child = viewGroup.getChildAt(i);
if (clazz.isAssignableFrom(child.getClass())) {
childrenFound.add((V)child);
}
if (child instanceof ViewGroup) {
gatherChildrenByClass((ViewGroup) child, clazz, childrenFound);
}
}
return childrenFound;
}
Ответ 5
Это лучше всего достигается с помощью пользовательских стилей. Перегрузите стиль виджета панели действий с помощью собственного стиля. Для голового света с темной панелью действия поместите это в свой собственный файл стилей, например res/values/styles_mytheme.xml
:
<style name="Theme.MyTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarWidgetTheme">@style/Theme.MyTheme.Widget</item>
<!-- your other custom styles -->
</style>
<style name="Theme.MyTheme.Widget" parent="@android:style/Theme.Holo">
<item name="android:textColorHint">@android:color/white</item>
<!-- your other custom widget styles -->
</style>
Убедитесь, что ваше приложение использует тему темы темы, как описано в введите описание ссылки здесь
Ответ 6
Для меня следующие работы.
Я использовал код из ссылки: Изменить цвет текста подсказки поиска в панели действий с помощью библиотеки поддержки.
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
EditText txtSearch = ((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
txtSearch.setHint(getResources().getString(R.string.search_hint));
txtSearch.setHintTextColor(Color.LTGRAY);
txtSearch.setTextColor(Color.WHITE);
Изменение цвета подсказки подсказки подсказки для подсказки подсказки подсказки предлагает другое решение. Он работает, но устанавливает только текст и цвет подсказки.
searchView.setQueryHint(Html.fromHtml("<font color = #ffffff>" + getResources().getString(R.string.search_hint) + "</font>"));
Ответ 7
Если вы используете android.support.v7.widget.SearchView, это возможно без необходимости использовать отражение.
Вот как я это делаю в своем приложении:
EditText text = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
ImageView searchCloseIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
View searchPlate = searchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
if (searchPlate != null) {
searchPlate.setBackgroundResource(R.drawable.search_background);
}
if (text != null){
text.setTextColor(resources.getColor(R.color.white));
text.setHintTextColor(getResources().getColor(R.color.white));
SpannableStringBuilder magHint = new SpannableStringBuilder(" ");
magHint.append(resources.getString(R.string.search));
Drawable searchIcon = getResources().getDrawable(R.drawable.ic_action_view_search);
int textSize = (int) (text.getTextSize() * 1.5);
searchIcon.setBounds(0, 0, textSize, textSize);
magHint.setSpan(new ImageSpan(searchIcon), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set the new hint text
text.setHint(magHint);
}
if (searchCloseIcon != null){
searchCloseIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_close));
}
Они не раскрывают идентификаторы публично для SearchView, но не Appcompat, но они делают для AppCompat, если вы знаете, где искать.:)
Ответ 8
Вы можете сделать это, установив атрибут editTextColor
в стиле.
<style name="SearchViewStyle" parent="Some.Relevant.Parent">
<item name="android:editTextColor">@color/some_color</item>
</style>
и вы применяете этот стиль к Toolbar
или SearchView
в макете.
<android.support.v7.widget.Toolbar
android:theme="@style/SearchViewStyle">
<android.support.v7.widget.SearchView />
</android.support.v7.widget.Toolbar>
Ответ 9
У меня была эта проблема, и это работает для меня.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.customer_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_customer_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
//Applies white color on searchview text
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
return true;
}
Ответ 10
Это сработало для меня: -
<style name="SearchTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:editTextColor">@android:color/white</item>
<item name="android:textColorHint">@color/deepblue</item>
<item name="android:textSize">16dp</item>
<item name="android:textColor">@color/darkdeepdray</item>
Ответ 11
Если вы основываете тему приложения на голой теме, вы получите белый вместо черного текста в SearchView
<style name="Theme.MyTheme" parent="android:Theme.Holo">
Я не нашел другого способа изменить цвет текста поиска без использования грязных хаков.
Ответ 12
Используйте это, это правильно.: D
AutoCompleteTextView searchText = (AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
searchText.setHintTextColor(getResources().getColor(color.black));
searchText.setTextColor(getResources().getColor(color.black));
Ответ 13
если вы используете - android.support.v7.widget.SearchView
SearchView searchView = (SearchView) item.getActionView();
EditText editText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
editText.setTextColor(Color.WHITE);
Ответ 14
Да, возможно использование следующего метода.
public static EditText setHintEditText(EditText argEditText, String argHintMessage, boolean argIsRequire) {
try {
if (argIsRequire) {
argHintMessage = " " + argHintMessage;
//String text = "<font color=#8c8c8c>"+argHintMessage+"</font> <font color=#cc0029>*</font>";
String text = "<font color=#8c8c8c>" + argHintMessage + "</font>";
argEditText.setHint(Html.fromHtml(text));
} else {
argEditText.setHint(argHintMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
return argEditText;
}
Вызов этого метода выглядит следующим образом.
metLoginUserName=(EditText)this.findViewById(R.id.etLoginUserName);
metLoginPassword=(EditText)this.findViewById(R.id.etLoginPassword);
/**Set the hint in username and password edittext*/
metLoginUserName=HotSpotStaticMethod.setHintEditText(metLoginUserName, getString(R.string.hint_username),true);
metLoginPassword=HotSpotStaticMethod.setHintEditText(metLoginPassword, getString(R.string.hint_password),true);
используя его, я успешно добавил красный цвет * mark в подсказку, используя этот метод.
Вы должны изменить этот метод в соответствии с вашим требованием.
Я надеюсь, что он вам полезен....:)
Ответ 15
Да, мы можем,
SearchView searchView = (SearchView) findViewById(R.id.sv_symbol);
Чтобы применить белый цвет для текста SerachView,
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
Счастливое кодирование!!!!
Ответ 16
Объект A SearchView
простирается от LinearLayout
, поэтому он содержит другие представления. Хитрость заключается в том, чтобы найти представление, содержащее текст подсказки и программно изменить цвет. Проблема с попыткой найти представление по id заключается в том, что идентификатор зависит от темы, используемой в приложении. Поэтому в зависимости от используемой темы метод findViewById(int id)
может возвращать null
. Лучшим подходом, который работает с каждой темой, является пересечение иерархии представлений и поиск виджета, содержащего текст подсказки:
// get your SearchView with its id
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// traverse the view to the widget containing the hint text
LinearLayout ll = (LinearLayout)searchView.getChildAt(0);
LinearLayout ll2 = (LinearLayout)ll.getChildAt(2);
LinearLayout ll3 = (LinearLayout)ll2.getChildAt(1);
SearchView.SearchAutoComplete autoComplete = (SearchView.SearchAutoComplete)ll3.getChildAt(0);
// set the hint text color
autoComplete.setHintTextColor(getResources().getColor(Color.WHITE));
// set the text color
autoComplete.setTextColor(Color.BLUE);
С помощью этого метода вы также можете изменить внешний вид других виджетов в иерархии SearchView
, например EditText
, содержащий поисковый запрос. Если Google не решит в ближайшее время изменить иерархию представления SearchView
, вы сможете изменить вид виджета с помощью этого метода в течение некоторого времени.
Ответ 17
Можно настроить поиск с помощью библиотеки appcompat v7. Для этого я использовал библиотеку appcompat v7 и определенный пользовательский стиль.
В выпадающей папке поместите файл bottom_border.xml, который выглядит следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape >
<solid android:color="@color/blue_color" />
</shape>
</item>
<item android:bottom="0.8dp"
android:left="0.8dp"
android:right="0.8dp">
<shape >
<solid android:color="@color/background_color" />
</shape>
</item>
<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="2.0dp">
<shape >
<solid android:color="@color/main_accent" />
</shape>
</item>
</layer-list>
В папках значений styles_myactionbartheme.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppnewTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/background</item>
<item name="android:actionBarStyle">@style/ActionBar</item>
<item name="android:actionBarWidgetTheme">@style/ActionBarWidget</item>
</style>
<!-- Actionbar Theme -->
<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">@color/main_accent</item>
<!-- <item name="android:icon">@drawable/abc_ic_ab_back_holo_light</item> -->
</style>
<style name="ActionBarWidget" parent="Theme.AppCompat.Light">
<!-- SearchView customization-->
<!-- Changing the small search icon when the view is expanded -->
<!-- <item name="searchViewSearchIcon">@drawable/ic_action_search</item> -->
<!-- Changing the cross icon to erase typed text -->
<!-- <item name="searchViewCloseIcon">@drawable/ic_action_remove</item> -->
<!-- Styling the background of the text field, i.e. blue bracket -->
<item name="searchViewTextField">@drawable/bottom_border</item>
<!-- Styling the text view that displays the typed text query -->
<item name="searchViewAutoCompleteTextView">@style/AutoCompleteTextView</item>
</style>
<style name="AutoCompleteTextView" parent="Widget.AppCompat.Light.AutoCompleteTextView">
<item name="android:textColor">@color/text_color</item>
<!-- <item name="android:textCursorDrawable">@null</item> -->
<!-- <item name="android:textColorHighlight">@color/search_view_selected_text</item> -->
</style>
</resources>
Я определил файл custommenu.xml для отображения меню:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.example.actionbartheme="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/search"
android:title="@string/search_title"
android:icon="@drawable/search_buttonn"
com.example.actionbartheme:showAsAction="ifRoom|collapseActionView"
com.example.actionbartheme:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
Ваша активность должна расширять ActionBarActivity вместо Activity.
Вот метод onCreateOptionsMenu.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custommenu, menu);
}
В файле манифеста:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppnewTheme" >
Для получения дополнительной информации см. этот URL:
Здесь http://www.jayway.com/2014/06/02/android-theming-the-actionbar/
Ответ 18
для панели инструментов appcompat-v7 с помощью searchView (предоставляется через MenuItemCompat):
Настройка темы панели инструментов на @style/ThemeOverlay.AppCompat.Light даст темный цвет (черный) для текста подсказки и для введенного текста, но не повлияет на цвет курсора *. Соответственно, настройка темы панели инструментов на @style/ThemeOverlay.AppCompat.Dark даст светлый цвет (белый) для текста подсказки и введенного текста, курсор * будет белым в любом случае.
Настройка тем выше:
android: textColorPrimary → цвет введенного текста
editTextColor → цвет введенного текста (переопределит влияние андроида: textColorPrimary, если установлено)
android: textColorHint → цвет подсказки
* Примечание: еще не удалось определить, как можно контролировать цвет курсора (без использования решения отражения).
Ответ 19
Используя это, я смог изменить напечатанный цветной текст в виде поиска
AutoCompleteTextView typed_text = (AutoCompleteTextView) inputSearch.findViewById(inputSearch.getContext().getResources().getIdentifier("android:id/search_src_text", null, null));
typed_text.setTextColor(Color.WHITE);
Ответ 20
это работает для меня.
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.white));
searchEditText.setHintTextColor(getResources().getColor(R.color.white));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
searchEditText.setBackgroundColor(getResources().getColor(R.color.c_trasnparent));
searchEditText.setGravity(Gravity.CENTER);
searchEditText.setCompoundDrawables(null,null,R.drawable.ic_cross,null);
}
Ответ 21
Ого. Много ответа. Он получает значение цвета из вашего основного цвета.
Измените его и сделайте!
@Override
public void onResume() {
super.onResume();
getActivity().setTheme(R.style.YourTheme_Searching);
}
Стили;
<style name="YourTheme.Searching" parent="YourTheme">
<item name="android:textColorPrimary">@android:color/white</item>
</style>
Ответ 22
Создайте стиль для Toolbar
<style name="AppTheme.Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
<item name="android:editTextColor">@color/some_color</item>
</style>
И установите его как тему для Toolbar
<android.support.v7.widget.Toolbar
android:theme="@style/AppTheme.Toolbar"
...
Ответ 23
Я попытался найти одно решение для этого. Я думаю, это поможет вам.
searchView.setBackgroundColor(Color.WHITE);
![enter image description here]()
Ответ 24
Измените цвет напечатанного текста:
((EditText)((SearchView)findViewById(R.id.searchView)).findViewById(((SearchView)findViewById(R.id.searchView)).getContext().getResources().getIdentifier("android:id/search_src_text", null, null))).setTextColor(Color.WHITE);
Измените цвет текста подсказки:
((EditText)((SearchView)findViewById(R.id.searchView)).findViewById(((SearchView)findViewById(R.id.searchView)).getContext().getResources().getIdentifier("android:id/search_src_text", null, null))).setHintTextColor(Color.LTGRAY);
Ответ 25
searchView = (SearchView) view.findViewById(R.id.searchView);
SearchView.SearchAutoComplete searchText = (SearchView.SearchAutoComplete) searchView
.findViewById(org.holoeverywhere.R.id.search_src_text);
searchText.setTextColor(Color.BLACK);
Я использую библиотеку Holoeverywhere. Обратите внимание на org.holoeverywhere.R.id.search_src_text
Ответ 26
TextView textView = (TextView) searchView.findViewById(R.id.search_src_text);
textView.setTextColor(Color.BLACK);
Ответ 27
Я нашел решение из сообщения в блоге. См. здесь.
В принципе вы в стиле searchViewAutoCompleteTextView и имеете android: actionBarWidgetTheme наследуют стиль.
Ответ 28
он работает со мной
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem searchItem = menu.findItem(R.id.action_search);
EditText searchEditText = (EditText) searchView.getActionView().findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.white));
searchEditText.setHintTextColor(getResources().getColor(R.color.white));
return super.onPrepareOptionsMenu(menu);
}
Ответ 29
Самый чистый способ:
На панели инструментов используется тема ThemeOverlay.AppCompat.Dark.Actionbar.
Теперь сделайте дочерний элемент таким, как:
toolbarStyle parent "ThemeOverlay.AppCompat.Dark.Actionbar"
добавить этот элемент в этот стиль
имя элемента "android: editTextColor" > yourcolor
Готово.
Еще одна важная вещь: на панели инструментов поместите layout_height = "? attr/actionbarSize". По умолчанию это wrap_content.For меня текст даже не был видимым в searchview, он исправил эту проблему.
Ответ 30
Вы можете реализовать этот класс, чтобы изменить цвет и изображение шрифта::
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.SearchAutoComplete;
public class MySearchView {
public static SearchView getSearchView(Context context, String strHint) {
SearchView searchView = new SearchView(context);
searchView.setQueryHint(strHint);
searchView.setFocusable(true);
searchView.setFocusableInTouchMode(true);
searchView.requestFocus();
searchView.requestFocusFromTouch();
ImageView searchBtn = (ImageView) searchView.findViewById(R.id.abs__search_button);
searchBtn.setImageResource(R.drawable.ic_menu_search);
ImageView searchBtnClose = (ImageView) searchView.findViewById(R.id.abs__search_close_btn);
searchBtnClose.setImageResource(R.drawable.ic_cancel_search_bar);
SearchAutoComplete searchText = (SearchAutoComplete) searchView.findViewById(R.id.abs__search_src_text);
searchText.setTextColor(context.getResources().getColor(color.white));
return searchView;
}
public static SearchView getSearchView(Context context, int strHintRes) {
return getSearchView(context, context.getString(strHintRes));
}
}
Надеюсь, это может помочь вам, ребята.
: D