为你的 Android 应用增加本地搜索功能(2)

/**
    * Initialize the action menu on action bar
    */
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_bar, menu);
 
        //set up the search
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) searchItem.getActionView();
        searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
                | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        //set up the query listener
        mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
              //start the search intent
              Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
              searchIntent.putExtra(SEARCH_MESSAGE, query);
                startActivity(searchIntent);
                return false;
            }
            @Override
            public boolean onQueryTextChange(String query) {
                //do nothing in our case
                return true;
            }
        });
       
        return super.onCreateOptionsMenu(menu);
    }

代码示例 3: 操作栏初始化代码

以及 SearchResultsActivity 类:

public class SearchResultsActivity extends Activity{
 
  TextView mQueryText;
  GridView searchListResults;
  SearchAdapter adapter;
  Vector<com.example.restaurant.MenuFactory.MenuItem> searchList;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    setContentView(R.layout.search_query_grid_results);
    mQueryText = (TextView) findViewById(R.id.txt_query);
 
    //setup the grid view
    searchListResults = (GridView)findViewById(R.id.search_results);
    searchList= new Vector<com.example.restaurant.MenuFactory.MenuItem>();
    //get and process search query here
    final Intent queryIntent = getIntent();
    doSearchQuery(queryIntent);
    adapter= new SearchAdapter(this,searchList);
    searchListResults.setAdapter(adapter);
 
    //Listener for grid view
    searchListResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment prev = getFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
          ft.remove(prev);
        }
        ft.addToBackStack(null);
        DialogFragment newFragment = SearchResultsDialogFragment.newInstance(searchList.elementAt(position));
        newFragment.show(ft, "dialog");
 
      }
    });
  }

代码示例 4: 主要的搜索结果类 (下面还会有)

当我们构建这个列表是,我们也将会处理没有查询到任何匹配项的情况下应该怎么做. 如果没有匹配,我们会查搜索的人显示一个消息对话框,让他们知晓,并且关闭搜索的activity,他们就不会看到一个空白的界面了.

/**
  * Builds the found item list.
  */
  private void doSearchQuery(final Intent queryIntent) {
    //Get the query text
    String message= queryIntent.getStringExtra(MainActivity.SEARCH_MESSAGE);
    //Set the UI field
    mQueryText.setText(message);
 
    RestaurantDatabase dB= new RestaurantDatabase(this);
    MenuFactory mMF= MenuFactory.getInstance();
    Cursor c= dB.searchMenuItems(message);
    Set<String> categories = new HashSet<String>();
    while (c.moveToNext()) {
      String category = c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.CATEGORY));
      categories.add(category);
 
      //build a new menu item and add it to the list
      MenuItem item= mMF.new MenuItem();
      item.setCategory(category);
      item.setName(c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.NAME)));
      item.setDescription(c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.DESCRIPTION)));
      item.setNutrition(c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.NUTRITION)));
      item.setPrice(c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.PRICE)));
      item.setImageName(c.getString(c.getColumnIndexOrThrow(RestaurantDatabase.MenuColumns.IMAGENAME)));
      searchList.add(item);
    }
    c.close();
 
    //Handle the case of not finding anything
    if(searchList.size()==0){
      Intent intent = new Intent(SearchResultsActivity.this, OrderViewDialogue.class);
      intent.putExtra(OrderViewActivity.DIALOGUE_MESSAGE, "Sorry, no matching items found.");
      startActivity(intent);
      SearchResultsActivity.this.finish();
    }
  }

代码示例 4 续

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/6c7c7650f580d408865dce461cc45d8d.html