Партнеры

Android: Using Search API

Мы осуществили новую возможность поиска в программе (см. скриншот ниже). В идеале , Поиск должен был быть осуществлен через “Фильтр поиска”, но из-за небольшого количества ошибок мы решили использовать” Поиск запрос”.
AndroidManifest.xml <activity android:name=".Images" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.app.default_searchable" android:value=".app.ImageSearch" /> </activity> - Добавлен мета-тег к активному изображению. - детальное объяснение всех доступных тегов в документации.. Всякий раз, когда поиск будет начат, ImageSearch будет запущен по умолчанию. <activity android:name="ImageSearch" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity> - Добавьте ImageSearch . This activity will receive and handle the search queries. searchable.xml <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:searchLabel="Images" /> - добавьте этот файл в res/xml/ Images.java public boolean onSearchRequested() { startSearch(null, null); return true;} - Это единственная часть дополнительного кода, которую мы добавим к существующему Images.java ImageSearch.java protected void onCreate(Bundle icicle) { super.onCreate(icicle); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); if (Intent.SEARCH_ACTION.equals(queryAction)) { doSearchQuery(queryIntent, "onCreate()"); } setContentView(R.layout.searchresult); GridView g = (GridView) findViewById(R.id.myGrid); g.setAdapter(new ImageAdapter(ImageSearch.this)); } - конструкция проверит, является ли полученный запрос SEARCH_ACTION. - - - результаты поиска будут показаны как GridView изображения. public void onNewIntent(final Intent newIntent) { super.onNewIntent(newIntent); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); if (Intent.SEARCH_ACTION.equals(queryAction)) { doSearchQuery(queryIntent, "onNewIntent()"); } } - Не используется. Включено только в объяснение. - Этот метод должен использоваться в двух случаях, a. Если сами результаты поиска (ImageSearch.java в этом случае) генерируют поиск. b. для того, чтобы осуществить Поиск фильтра. private void doSearchQuery(final Intent queryIntent, final String entryPoint) { result = new ArrayList(); queryString = queryString + queryIntent.getStringExtra(SearchManager.QUERY); setTitle("Search results for "+"'"+queryString+"'"); for(String file : Images.mFiles) { if(file.contains(queryString)) { result.add(file); } } mUris = new Uri[result.size()]; for(int i=0; i < result.size(); i++) { mUris[i] = Uri.parse(result.get(i)); } } - В этом методе мы будем использовать запрос, который мы получили из массива mFiles - queryString будет хранить пользовательский запрос -результат ArrayList будет хранить путь всех рисунков образов, которые соответствуют запросу - From the result ArrayList, paths will be passed on to the Uri array and then to the ImageAdapter, like in the case of Images.java. - из результата ArrayList, пути будут переданы в массив Uri, а затем ImageAdapter’у, как и в случае Images.java ImageSearch.java состоит еще из некоторых методов и классов, но они подобны построенным таким же в Images.java, исключая то, что там мы использовали Галерею, и здесь мы используем GridView.
Код Код для Images.java остается тем же самым за исключением маленького метода, упомянуто выше. AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tp.proj"> <application android:icon="@drawable/icon"> <activity android:name=".Images" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.app.default_searchable" android:value=".app.ImageSearch" /> </activity> <!-- Search Activity --> <activity android:name="ImageSearch" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity> </application> </manifest> res/xml/searchable.xml <?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:searchLabel="Images"/> searchresult.xml (Layout for ImageSearch) ImageSearch.java public class ImageSearch extends Activity { String queryString = ""; ArrayList result; String oldQuery=null; String[] resultarray; private Uri[] mUris; protected void onCreate(Bundle icicle) { super.onCreate(icicle); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); if (Intent.SEARCH_ACTION.equals(queryAction)) { doSearchQuery(queryIntent, "onCreate()"); } setContentView(R.layout.searchresult); GridView g = (GridView) findViewById(R.id.myGrid); g.setAdapter(new ImageAdapter(ImageSearch.this)); } public View makeView() { ImageView i = new ImageView(this); i.setBackgroundColor(0xFF000000); i.setScaleType(ImageView.ScaleType.CENTER_CROP); i.setLayoutParams(new LayoutParams(80,80)); return i; } @Override public void onNewIntent(final Intent newIntent) { super.onNewIntent(newIntent); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); if (Intent.SEARCH_ACTION.equals(queryAction)) { doSearchQuery(queryIntent, "onNewIntent()"); } } public class ImageAdapter extends BaseAdapter { public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mUris.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); i.setImageURI(mUris[position]); i.setLayoutParams(new Gallery.LayoutParams(120, 100)); i.setAdjustViewBounds(false); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setPadding(8, 10, 16, 8); return i; } private Context mContext; } private void doSearchQuery(final Intent queryIntent, final String entryPoint) { result = new ArrayList(); queryString = queryString + queryIntent.getStringExtra(SearchManager.QUERY); setTitle("Search results for "+"'"+queryString+"'"); for(String file : Images.mFiles) { if(file.contains(queryString)) { result.add(file); } } mUris = new Uri[result.size()]; for(int i=0; i < result.size(); i++) { mUris[i] = Uri.parse(result.get(i)); } } }