Android开发之搜索框应用(二)

分类: Android开发系列 1713人阅读 评论(3) 收藏 举报

      今天要讲的是搜索框应用系列(二),说道搜索框的应用其实并不难,而是在于它的配置非常之繁琐,对于它的使用主要是方便开发者对于程序中有搜索业务时,更好的设计UI。

       今天的应用主要实现的效果是和google搜索一样,实现联想功能,如用户输入a,列表中则显示以a开头的数据库中的信息。下面是实现的效果图:

   

                                            图(一)                                                                                                  图(二)

                                        图(三)

图(一):当运行项目时,首先出现的界面,该界面简单,就一个Button和TextView,当单击button按钮时,会跳转到图(二);

图(二):进行相关信息的搜索,为用户提供搜索服务,输入信息,然后就会跳转到图(三);

图(三):用于显示搜索出得信息。

实现过程如下:

  • 实现过程主要是添加所有的数据到数据库中。
  • 调用搜索控件。
  • 根据用户输入的信息显示联想的所有词的列表。
  • 根据用户选择,显示相应的结果。

下面来详细的开发本项目。

1、创建一个Android项目,命名为SearchManager。

2、新建一个位于res/xml下的一个searchable.xml(该文件名称可以改动,不一定非要用这个,我试过!)的配置文件,文件内容具体如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <searchable xmlns:android="http://schemas.android.com/apk/res/android"  
  3.   android:label="@string/search_label"   
  4.   android:searchSuggestAuthority="search"   
  5.   android:searchSuggestIntentAction="android.intent.action.VIEW"   
  6.   />  

3、在layout文件夹下新建一个文件,为result.xml具体内容和main.xml的代码如下:

main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:background="@drawable/hao">  
  7.     <TextView   
  8.        android:layout_width="fill_parent"   
  9.        android:layout_height="wrap_content"   
  10.        android:text="测试一下搜索" />   
  11.     <Button   
  12.        android:layout_width="fill_parent"   
  13.        android:layout_height="wrap_content"   
  14.        android:id="@+id/button"   
  15.        android:text="搜索" />   
  16. </LinearLayout>  

result.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:background="@drawable/hao">  
  7.     <TextView   
  8.        android:layout_width="fill_parent"   
  9.        android:id="@+id/test"   
  10.        android:layout_height="wrap_content"   
  11.        android:text="搜索结果" />  
  12. </LinearLayout>  

4、修改value文件夹下的string.xml代码,内容如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   <string name="hello">Hello World, SearchActivty!</string>   
  4.   <string name="app_name">Search</string>   
  5.   <string name="search_label">xxxs</string>   
  6.   <string name="settings_description">Definitions of words</string>   
  7.   <string name="search_invoke">sss</string>   
  8.   <string name="search_query_results">ssdsadws</string>   
  9. </resources>  

5、向drawable-mdpi文件夹中导入一张背景图片,该图片可以任意!在这里我就不说了。

6、修改主Activity,SearchActivity.java内容代码如下:

  1. public class SearchActivity extends Activity {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         //获取Intent对象  
  6.         Intent intent = this.getIntent();  
  7.         //布局  
  8.         setContentView(R.layout.main);  
  9.         //判断intent的action是否等于action-view  
  10.         if (Intent.ACTION_VIEW.equals(intent.getAction())) {  
  11.             SearchUtil.Word theWord = SearchUtil.getInstance().getMatches(  
  12.                     intent.getDataString().trim().toLowerCase()).get(0);  
  13.             launchWord(theWord);  
  14.             finish();  
  15.         } else {  
  16.         //取得按钮对象  
  17.         Button button = (Button) findViewById(R.id.button);  
  18.         //注册按钮单击事件  
  19.         button.setOnTouchListener(new OnTouchListener() {  
  20.             @Override  
  21.             public boolean onTouch(View v, MotionEvent event) {  
  22.                 onSearchRequested();  
  23.                 return false;  
  24.             }  
  25.         });  
  26.     }  
  27.     }  
  28.     //存储值,进行界面跳转  
  29.     private void launchWord(SearchUtil.Word pavilion) {  
  30.         Intent next = new Intent();  
  31.         next.setClass(this, ResultActivty.class);  
  32.         Bundle bundle = new Bundle();  
  33.         bundle.putString("word", pavilion.word);  
  34.         next.putExtras(bundle);  
  35.         next.putExtras(bundle);  
  36.         startActivity(next);  
  37.     }  
  38. }  

7、新建一个Activity,我们命名为ResultActivity.java用于显示搜索结果,该文件的内容代码如下:

  1. public class ResultActivty extends Activity{  
  2.     @Override  
  3.     protected void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.result);  
  6.         //取得bundle对象  
  7.         Bundle bundle = this.getIntent().getExtras();  
  8.         //取得bundle中的信息  
  9.         String word = bundle.getString("word");  
  10.         //获取textView对象  
  11.         TextView textView=(TextView)findViewById(R.id.test);  
  12.         //把该信息显示在textView中  
  13.         textView.setText("搜索结果:"+word);  
  14.     }  
  15. }  

8、新建一个类SearchProvider,该类继承了ContentProvider,用于数据存储和查询,具体代码如下:

  1. public class SearchProvider extends ContentProvider {  
  2.     @Override  
  3.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  4.         return 0;  
  5.     }  
  6.     @Override  
  7.     public String getType(Uri uri) {  
  8.         return null;  
  9.     }  
  10.     @Override  
  11.     public Uri insert(Uri uri, ContentValues values) {  
  12.         return null;  
  13.     }  
  14.     @Override  
  15.     public boolean onCreate() {  
  16.         // 添加所有的数据  
  17.         SearchUtil.getInstance().ensureLoaded();  
  18.         return true;  
  19.     }  
  20.     @Override  
  21.     public Cursor query(Uri uri, String[] projection, String selection,  
  22.             String[] selectionArgs, String sortOrder) {  
  23.         String query = null;  
  24.         if (uri.getPathSegments().size() > 1) {  
  25.             query = uri.getLastPathSegment().toLowerCase();  
  26.         }  
  27.         return getSuggestions(query);  
  28.     }  
  29.     private Cursor getSuggestions(String query) {  
  30.         String processedQuery = query == null ? "" : query.toLowerCase();  
  31.         List<SearchUtil.Word> words = SearchUtil.getInstance().getMatches(  
  32.                 processedQuery);  
  33.         MatrixCursor cursor = new MatrixCursor(COLUMNS);  
  34.         long id = 0;  
  35.         for (SearchUtil.Word word : words) {  
  36.             cursor.addRow(columnValuesOfWord(id++, word));  
  37.         }  
  38.         return cursor;  
  39.     }  
  40.     private Object[] columnValuesOfWord(long id, SearchUtil.Word word) {  
  41.         return new Object[] { id, // _id  
  42.                 word.word, // text1  
  43.                 word.definition, // text2  
  44.                 word.word, // intent_data (included when clicking on item)  
  45.         };  
  46.     }  
  47.     private static final String[] COLUMNS = { "_id",  
  48.             SearchManager.SUGGEST_COLUMN_TEXT_1,  
  49.             SearchManager.SUGGEST_COLUMN_TEXT_2,  
  50.             SearchManager.SUGGEST_COLUMN_INTENT_DATA,// 数据传递到intenter中  
  51.     };  
  52.     @Override  
  53.     public int update(Uri uri, ContentValues values, String selection,  
  54.             String[] selectionArgs) {  
  55.         return 0;  
  56.     }  
  57. }  

9、新建一个SearchUtil类,便于管理,相关代码具体如下:

  1. public class SearchUtil {  
  2.     public static class Word {  
  3.         public final String word;  
  4.         public final String definition;  
  5.         public Word(String word, String definition) {  
  6.             this.word = word;  
  7.             this.definition = definition;  
  8.         }  
  9.     }  
  10.     private static final SearchUtil sInstance = new SearchUtil();  
  11.     private final Map<String, List<Word>> mDict = new ConcurrentHashMap<String, List<Word>>();  
  12.     public static SearchUtil getInstance() {  
  13.         return sInstance;  
  14.     }  
  15.     private SearchUtil() {  
  16.     }  
  17.     private boolean mLoaded = false;  
  18.     public synchronized void ensureLoaded() {  
  19.             if (mLoaded) return;  
  20.             new Thread(new Runnable() {  
  21.                 public void run() {  
  22.                     //插入数据  
  23.                     addWord("a", "aaa");  
  24.                     addWord("aa", "aaa");  
  25.                     addWord("aaa", "aaa");  
  26.                 }  
  27.             }).start();  
  28.         }  
  29.       @SuppressWarnings("unchecked")  
  30.     public List<Word> getMatches(String query) {  
  31.             List<Word> list = mDict.get(query);  
  32.             return list == null ? Collections.EMPTY_LIST : list;  
  33.         }  
  34.     private void addWord(String word, String definition) {  
  35.             final Word theWord = new Word(word, definition);  
  36.   
  37.             final int len = word.length();  
  38.             for (int i = 0; i < len; i++) {  
  39.                 final String prefix = word.substring(0, len - i);  
  40.                 addMatch(prefix, theWord);  
  41.             }  
  42.         }  
  43.         private void addMatch(String query, Word word) {  
  44.             List<Word> matches = mDict.get(query);  
  45.             if (matches == null) {  
  46.                 matches = new ArrayList<Word>();  
  47.                 mDict.put(query, matches);  
  48.             }  
  49.             matches.add(word);  
  50.         }  
  51. }  

10、就是相关搜索的配置了,这里需要注意!具体代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.wyf.wpf"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.   
  8.     <application android:icon="@drawable/skey" android:label="@string/app_name">  
  9.         <activity android:name=".SearchActivity"  
  10.                   android:label="@string/app_name">  
  11.             <intent-filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent-filter>  
  15.             <intent-filter>  
  16.                 <!-- 这里也不能忽略 -->  
  17.                 <action android:name="android.intent.action.SEARCH" />   
  18.                 <category android:name="android.intent.category.DEFAULT" />   
  19.             </intent-filter>  
  20.             <!-- 指定上面的searchable.xml文件 -->  
  21.             <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />   
  22.         </activity>  
  23.         <activity android:name=".ResultActivty" android:label="@string/search_query_results" />   
  24.         <!--之前searchable.xml中有一个searchSuggestAuthority的值其实和这里的authorities是相同的,这点药注意-->  
  25.         <provider android:name="SearchProvider" android:authorities="search" android:syncable="false" />  
  26.     </application>  
  27. </manifest>  

到此,整个项目就开发完毕,单击运行便会得到以上效果。

posted on 2013-01-17 23:48  zhengbeibei  阅读(8319)  评论(1编辑  收藏  举报