Vin*_*rat 9 android android-3.0-honeycomb
我有一个字段,用户可以在应用程序的操作栏中键入搜索查询.这是在操作栏中使用活动中的菜单膨胀声明的:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="@+id/action_search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
android:title="@string/search"
></item>
</menu>
Run Code Online (Sandbox Code Playgroud)
我需要自定义SearchView的外观(例如背景和文本颜色).到目前为止,我找不到使用XML(使用样式或主题)的方法.
在给菜单充气时,我唯一的选择是在代码中执行此操作吗?
编辑#1:我已经尝试过编程,但我无法通过简单的方法设置文本颜色.另外,当我做searchView.setBackgroundResource(...)的背景被设定在全局Widget(也当搜索查看图标化).
编辑#2:在没有太多信息的搜索开发人员参考任
如果你想改变图标,Seibelj有一个很好的答案.但是您需要为每个API版本执行此操作.我正在使用带有ActionBarSherlock的ICS,它对我不公平,但确实让我朝着正确的方向前进.
下面我改变文字颜色和提示颜色.我展示了你如何改变图标,虽然我现在对此没有兴趣(你可能想要使用默认图标来保持一致)
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Set up the search menu
SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
traverseView(searchView, 0);
return true;
}
private void traverseView(View view, int index) {
if (view instanceof SearchView) {
SearchView v = (SearchView) view;
for(int i = 0; i < v.getChildCount(); i++) {
traverseView(v.getChildAt(i), i);
}
} else if (view instanceof LinearLayout) {
LinearLayout ll = (LinearLayout) view;
for(int i = 0; i < ll.getChildCount(); i++) {
traverseView(ll.getChildAt(i), i);
}
} else if (view instanceof EditText) {
((EditText) view).setTextColor(Color.WHITE);
((EditText) view).setHintTextColor(R.color.blue_trans);
} else if (view instanceof TextView) {
((TextView) view).setTextColor(Color.WHITE);
} else if (view instanceof ImageView) {
// TODO dissect images and replace with custom images
} else {
Log.v("View Scout", "Undefined view type here...");
}
}
Run Code Online (Sandbox Code Playgroud)
添加我对不同Android版本可能更高效和安全的东西的看法.
您实际上可以从字符串ID名称获取数字ID值.使用android的hierarchyviewer工具,你实际上可以找到你感兴趣的东西的字符串ID,然后用它findViewById(...)来查找它们.
下面的代码设置编辑字段本身的提示和文本颜色.您可以将相同的模式应用于您希望设计样式的其他方面.
private static synchronized int getSearchSrcTextId(View view) {
if (searchSrcTextId == -1) {
searchSrcTextId = getId(view, "android:id/search_src_text");
}
return searchSrcTextId;
}
private static int getId(View view, String name) {
return view.getContext().getResources().getIdentifier(name, null, null);
}
@TargetApi(11)
private void style(View view) {
ImageView iv;
AutoCompleteTextView actv = (AutoCompleteTextView) view.findViewById(getSearchSrcTextId(view));
if (actv != null) {
actv.setHint(getDecoratedHint(actv,
searchView.getContext().getResources().getString(R.string.titleApplicationSearchHint),
R.drawable.ic_ab_search));
actv.setTextColor(view.getContext().getResources().getColor(R.color.ab_text));
actv.setHintTextColor(view.getContext().getResources().getColor(R.color.hint_text));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该属性android:actionLayout来指定要膨胀的布局。只需拥有一个布局SearchView,您就不必真正修改任何内容。
至于更改 上的文本样式SearchView可能是不可能的,因为它SearchView是ViewGroup. 您可能应该尝试通过主题更改文本颜色。