package com.example.excerciseforsearchview; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.app.SearchManager; import android.app.SearchableInfo; import android.content.Context; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements SearchView.OnQueryTextListener{ TextView textView; private SearchView searchView; private SearchableInfo searchableInfo; private SearchableInfo shInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView=(TextView) findViewById(R.id.text); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); MenuItem menuItem=menu.findItem(R.id.action_settings); //下面一行代碼的做用是Returns the currently set action view for this menu item. //要使用menuItem的getActionView方法需在設置menu的xml文件item裏添加 //android:actionViewClass="android.widget.SearchView" searchView=(SearchView) menuItem.getActionView(); searchView.setOnQueryTextListener(this); searchAppInfo(); return true; } private void searchAppInfo() { // TODO Auto-generated method stub SearchManager searchManager=(SearchManager) getSystemService(Context.SEARCH_SERVICE); if (searchManager!=null) { //Returns a list of the searchable activities that can be included in global search. //把全部能夠被搜索到的Searchable activities列出 List<SearchableInfo> searchableInfos=searchManager.getSearchablesInGlobalSearch(); //Gets information about a searchable activity //根據ComponentName獲得具體搜到的searchableInfo searchableInfo=searchManager.getSearchableInfo(getComponentName()); for (SearchableInfo sInfo:searchableInfos) { if (sInfo.getSuggestAuthority()!=null&&sInfo.getSuggestAuthority().startsWith("application")) { searchableInfo=sInfo; } } } //Sets the SearchableInfo for this SearchView. //Properties in the SearchableInfo are used to display //labels, hints, suggestions, create intents //for launching search results screens and controlling other affordances such as a voice button. searchView.setSearchableInfo(searchableInfo); } @Override public boolean onQueryTextChange(String newText) { // TODO Auto-generated method stub return false; } @Override public boolean onQueryTextSubmit(String query) { // TODO Auto-generated method stub textView.append(query); return false; } }