步骤1 将SearchView作为OptionMenu的一个Item
res/menu/option_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LauncherActivity">
<item
android:id="@+id/search_view"
android:title="搜索"
android:icon="@mipmap/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
</menu>
步骤2 设置SearchView的相关属性
MainActivity.java
package com.example.jun.searchviewtest;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SearchView mSearchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
MenuItem item = menu.findItem(R.id.search_view);
//通过MenuItem的兼容版MenuItemCompat获取SearchView
mSearchView = (SearchView) MenuItemCompat.getActionView(item);
//监听搜索框
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//提交搜索框内容,确定搜索
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(MainActivity.this, "确定搜索", Toast.LENGTH_SHORT).show();
return true;
}
//搜索框内容改变
@Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(MainActivity.this, "搜索框内容改变了", Toast.LENGTH_SHORT).show();
return true;
}
});
return true;
}
}