Ответ 1
android: actionBarWidgetTheme вашей основной темы должен указывать на стиль, в котором есть android: textColorHint. Это позволит изменить цвет текста подсказки в виде поиска.
Как изменить цвет текста подсказки в строке поиска поиска?
Этот вопрос объясняет, как получить EditText при использовании ABS: Android ActionBar Настроить вид поиска
Есть ли файл android.R.id, который я мог бы использовать для получения ссылки на EditText, чтобы изменить цвет подсказки? Или есть другой способ изменить цвет?
android: actionBarWidgetTheme вашей основной темы должен указывать на стиль, в котором есть android: textColorHint. Это позволит изменить цвет текста подсказки в виде поиска.
searchView.setQueryHint(Html.fromHtml("<font color = #ffffff>" + getResources().getString(R.string.hintSearchMess) + "</font>"));
SearchView searchView= (SearchView) findViewById(R.id.searchView1);
int id = searchView.getContext()
.getResources()
.getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
Я решил добавить это свойство в основную тему:
<style name="AppTheme" parent="AppBaseTheme">
.....
.....
<item name="android:actionBarWidgetTheme">@style/MyActionBarWidgetTheme</item>
</style>
И затем добавьте свойство, которое я хочу изменить в этом случае цветом подсказки.
<style name="MyActionBarWidgetTheme" parent="@android:style/Theme.Holo">
.....
.....
<item name="android:textColorHint">@color/blanco_60</item>
</style>
Надеюсь, что это поможет: D
это сработало для меня, надеюсь, что это поможет
((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(getResources().getColor(R.color.white));
Объект A SearchView
простирается от LinearLayout
, поэтому он содержит другие представления. Хитрость заключается в том, чтобы найти представление, содержащее текст подсказки и программно изменить цвет. Перейдя по иерархии представлений, вы можете найти виджет, содержащий текст подсказки:
// 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));
Этот метод работает с любой темой. Кроме того, вы можете изменить внешний вид других виджетов в иерархии SearchView
, например EditText
, содержащий поисковый запрос.
Здесь конкретно, как вы применяете стиль, как указано выше. Правильный ответ - перегрузить стиль виджета панели действий с помощью собственного стиля. Для голового света с темной панелью действия поместите это в свой собственный файл стилей, например 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>
Убедитесь, что ваше приложение использует тему темы, как описано в введите ссылку здесь
Просто найдите идентификатор textView
виджета поиска и используйте метод setTextColor()
, чтобы изменить цвет текста поиска и setHintTextColor()
, чтобы изменить цвет текста подсказок поиска.
// Get textview id of search widget
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
// Set search text color
textView.setTextColor(Color.WHITE);
// Set search hints color
textView.setHintTextColor(Color.GRAY);
Посмотрите на этот класс, он поможет вам решить вашу проблему.
import android.R.color;
import android.content.Context;
import android.graphics.Typeface;
import android.widget.ImageView;
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);
setFont(context, searchText);
searchText.setTextColor(context.getResources().getColor(color.white));
searchText.setHintTextColor(context.getResources().getColor(color.white));
return searchView;
}
private static void setFont(Context _context, SearchAutoComplete searchText) {
Typeface tf = null;
Typeface currentType = searchText.getTypeface();
if (currentType == null) {
tf = MyApplication.fontNormal;
}
else {
int currentStyle = currentType.getStyle();
if (currentStyle == Typeface.BOLD) {
tf = MyApplication.fontBold;
}
else if (currentStyle == Typeface.BOLD_ITALIC) {
tf = MyApplication.fontBoldItalic;
}
else if (currentStyle == Typeface.ITALIC) {
tf = MyApplication.fontItalic;
}
else {
tf = MyApplication.fontNormal;
}
}
searchText.setTypeface(tf);
}
public static SearchView getSearchView(Context context, int strHintRes) {
return getSearchView(context, context.getString(strHintRes));
}
}
Если вы хотите изменить кнопку со стрелкой влево в окне поиска, добавьте приложение: collapseIcon.
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:collapseIcon="@drawable/ic_search_view_home"
/>
Если вы хотите изменить цвет текста и цвет текста, добавьте следующее.
EditText searchEditText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(Color.WHITE);
searchEditText.setHintTextColor(Color.WHITE);
Если вы хотите изменить значок закрытия, добавьте следующее.
ImageView imvClose = searchView.findViewById(android.support.v7.appcompat.R.id
.search_close_btn);
imvClose.setImageResource(R.drawable.ic_search_view_close);
Также вы можете настроить SearchView на свой элемент меню вручную и тем самым полностью контролировать представление.
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(Color.WHITE);
textView.setHintTextColor(Color.WHITE);
С помощью этого вы можете изменить поисковый xml
int searchHintBtnId = searchView.getContext().getResources() .getIdentifier("android:id/search_mag_icon", null, null); int hintTextId = searchView.getContext() .getResources() .getIdentifier("android:id/search_src_text", null, null); int closeBtnId = searchView.getContext() .getResources() .getIdentifier("android:id/search_close_btn", null, null); // Set the search plate color to white int searchPlateId = getResources().getIdentifier("android:id/search_plate", null, null); View view = searchView.findViewById(searchPlateId); view.setBackgroundResource(R.drawable.search_plate); ImageView closeIcon = (ImageView) searchView.findViewById(closeBtnId); closeIcon.setImageResource(R.drawable.close); ImageView searchHintIcon = (ImageView) searchView.findViewById(searchHintBtnId); searchHintIcon.setImageResource(R.drawable.search); TextView textView = (TextView) searchView.findViewById(hintTextId); textView.setTextColor(getResources().getColor(R.color.search_text_color)); textView.setHintTextColor(getResources().getColor(R.color.search_hint_text_color));
Вот вытаскиваемый /search _plate.xml
<!-- main color --> <item android:bottom="1dp" android:left="1dp" android:right="1dp"> <shape > <solid android:color="@color/app_theme_color" /> </shape> </item> <!-- draw another block to cut-off the left and right bars --> <item android:bottom="10.0dp"> <shape > <solid android:color="@color/app_theme_color" /> </shape> </item> </layer-list>
Попробуйте этот код. Это очень легко.
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setHint("Search");
searchEditText.setHintTextColor(getResources().getColor(R.color.white));
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchEditText.setHintTextColor(. GetResources() GetColor (R.color.white));
Решение изменить цвет текста подсказки для поиска в виде поиска:
SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchAutoComplete.setHintTextColor(Color.GRAY);
Это очень просто достичь с помощью styles.xml
Просто поймите, что тема SearchView напрямую связана с темой панели инструментов, из которой menu.xml
она выбирается как app:actionViewClass
.
С самой последней библиотекой appcompat (или если вы нацеливаетесь на 5.0+), это можно сделать чисто в XML с помощью ThemeOverlay
:
<style name="ThemeOverlay.MyApp.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
<item name="autoCompleteTextViewStyle">@style/Widget.MyApp.AutoCompleteTextView.SearchView</item>
</style>
<style name="Widget.MyApp.AutoCompleteTextView.SearchView" parent="Widget.AppCompat.AutoCompleteTextView">
<item name="android:textColor">#000</item>
<item name="android:textColorHint">#5000</item>
</style>
И затем в вашем файле макета:
<android.support.v7.widget.Toolbar
app:theme="@style/ThemeOverlay.MyApp.ActionBar"
... />
Если вы также хотите, чтобы он применялся к действиям, использующим ActionBar
вместо Toolbar
, вы можете добавить это в тему Activity
:
<style name="Theme.MyApp" parent="Theme.AppCompat">
<item name="actionBarTheme">@style/ThemeOverlay.MyApp.ActionBar</item>
...
</style>
Поместите это в свой XML файл:
android:textColorHint="@android:color/white"