Android SearchView和其他Android View類似,直接可以作為一個View使用,現在給出一個最簡單的SearchView使用方式。在後續的文章中,将一步一步由淺入深從簡單到複雜介紹其他Android系統的搜尋功能(如搜尋聯想和搜尋建議)。
MainActivity.java
package zhangphil.searchview;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class MainActivity extends ActionBarActivity {
private SearchView mSearchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchView = (SearchView) findViewById(R.id.search);
mSearchView.setIconifiedByDefault(true);
mSearchView.setFocusable(false);
mSearchView.clearFocus();
mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String queryText) {
System.out.println("onQueryTextChange:"+queryText);
return true;
}
@Override
public boolean onQueryTextSubmit(String queryText) {
System.out.println("onQueryTextSubmit:"+queryText);
return true;
}
});
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SearchView
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>