安卓组件之SearchView

添加SearchView到Toolbar中

  • res/menu/新建一个名为search_view的xml文件,
    

android:actionViewClass="android.widget.SearchView"
android:id="@+id/searchView"
android:orderInCategory="100"
android:title="@string/app_name"
android:icon="@drawable/ic_search_white"
app:showAsAction="collapseActionView|ifRoom"/>

```
app:showAsAction="collapseActionView|ifRoom"控制默认为隐藏

  • 初始化Toolbar,更改 res/values/styles中的
    parent= "Theme.AppCompat.Light.DarkActionBar
    parent= "Theme.AppCompat.Light.NoActionBar

  • MainActivity 中覆写 onCreateOptionsMenu(Menu menu)方法,

```

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_view,menu);
setSearchView(menu);
return true;
}


- 初始化SearchView

private void setSearchView(Menu menu) {
MenuItem item = menu.getItem(0);
searchView = new SearchView(this);
//设置展开后图标的样式,false时ICON在搜索框外,true为在搜索框内,无法修改
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("搜索");
searchView.setSubmitButtonEnabled(true);//设置最右侧的提交按钮
item.setActionView(searchView);
}

  现在的样式:
![未展开状态](http://upload-images.jianshu.io/upload_images/3643041-b76999ed548c5cc8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![展开状态](http://upload-images.jianshu.io/upload_images/3643041-caa8f46bafbcf40f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


### 自定义样式
- ##### 通过获取SearchView 中各组件的id来改变样式

mSearchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text);//输入框文字
mSearchButton = (ImageView) findViewById(R.id.search_button);
mGoButton = (ImageView) findViewById(R.id.search_go_btn);//右侧提交按钮
mCloseButton = (ImageView) findViewById(R.id.search_close_btn);//右侧关闭按钮(输入文字后出现的x)
mVoiceButton = (ImageView) findViewById(R.id.search_voice_btn);//语音输入按钮
mCollapsedIcon = (ImageView) findViewById(R.id.search_mag_icon);//输入框内Icon

*SearchView源码310行左右* 
  - 设置输入文字的样式

TextView textView = (TextView)searchView
.findViewById(android.support.v7.appcompat.R.id.search_src_text);
textView.setHintTextColor(Color.WHITE); //hint文字颜色
textView.setTextColor(Color.WHITE); //输入的文字颜色


 - 设置关闭按钮

ImageView closeButton = (ImageView)searchView
.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
closeButton.setImageDrawable(getDrawable(R.drawable.ic_close_white)); //设置为自己定义的Icon

 - 别的设置方法都一样,拿到组件id即可进行设置。
- ##### 输入框内隐藏Icon的设置
**输入框内的搜索图标只有在 ` setIconifiedByDefault(false)  `时才能设置成功。**
当 ` setIconifiedByDefault(false)  `时,

//设置Icon是否在输入框内部
public void setIconifiedByDefault(boolean iconified) {
//设置为false将直接返回
if (mIconifiedByDefault == iconified) return;
mIconifiedByDefault = iconified;
updateViewsVisibility(iconified);
updateQueryHint();
}


` mIconifiedByDefault `为一个` boolean `变量,在对象初始化时被默认初始化为` false `,所以设置为` false `就会直接返回,不再设置输入框中的Icon。
而设置为` true `时,进入` updateQueryHint() ` 方法:

//更新输入框中的Hint内容
private void updateQueryHint() {
final CharSequence hint = getQueryHint();
mSearchSrcTextView.setHint(getDecoratedHint(hint == null ? "" : hint));
}

再次跳转进入` getDecoratedHint(CharSequence hintText) `方法:

//得到Hint内容
private CharSequence getDecoratedHint(CharSequence hintText) {
// If the field is always expanded or we don't have a search hint icon,
// then don't add the search icon to the hint.
if (!mIconifiedByDefault || mSearchHintIcon == null) {
return hintText;
}
final int textSize = (int) (mSearchSrcTextView.getTextSize() * 1.25);
//在这里设置Icon位置
mSearchHintIcon.setBounds(0, 0, textSize, textSize);
final SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.setSpan(new ImageSpan(mSearchHintIcon), 1, 2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(hintText);
return ssb;
}

而` mSearchHintIcon `定义为私有的变量

private final Drawable mSearchHintIcon;

所以无法设置。

![现在的样式 ](http://upload-images.jianshu.io/upload_images/3643041-1705f94c3bd77866.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)





### 传递搜索字符串
两种方法均可
1. 实现`SearchView.OnQueryTextListener  `接口,在` onQueryTextSubmit `和` onQueryTextChange `中处理搜索请求
2. 创建一个检索配置,利用系统的SearchManager进行管理
 - 创建检索配置
在 ` res/xml/ ` 创建 ` searchable.xml `


xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint" />

 - 关联检索配置与SearchView
   在含有`SearchView `的活动(Activiy)的 ` onCreateOptionsMenu(Menu menu) `中添加

SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
SearchableInfo searchableInfo =
searchManager.getSearchableInfo(
new ComponentName(getApplicationContext(), SearcherAty.class));
searchView.setSearchableInfo(searchableInfo);

> 调用[getSearchableInfo()](http://developer.android.com/reference/android/app/SearchManager.html#getSearchableInfo(android.content.ComponentName))返回一个[SearchableInfo](http://developer.android.com/reference/android/app/SearchableInfo.html)由检索配置XML文件创建的对象。检索配置与[SearchView](http://developer.android.com/reference/android/widget/SearchView.html)正确关联后,当用户提交一个搜索请求时,[SearchView](http://developer.android.com/reference/android/widget/SearchView.html)会以[ACTION_SEARCH](http://developer.android.com/reference/android/content/Intent.html#ACTION_SEARCH) intent启动一个activity。
 - 新建一个Activity来处理搜索
  ` SearcherAty `
 - 修改AndroidManifest配置
  在包含这个` SearchView ` 的` activity `的` AndroidManifest ` 中添加


...
android:name="android.app.searchable"
android:resource="@xml/searchable" />

在`SearchAty `中添加

android:label="@string/search_label"
android:launchMode="singleTop">





android:name="android.app.searchable"
android:resource="@xml/searchable"/>


 - 接收检索字符串

@Override
public void onCreate(Bundle savedInstanceState) {
...
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//通过某种方法,根据请求检索你的数据
}
}


### 项目地址 ` https://github.com/YangLuYang/android-Widget-SearchView `

你可能感兴趣的:(安卓组件之SearchView)