搜索是应用于大量的AndroID应用程序的功能。提供一种方法来搜索您的应用程序中的内容是非常重要的,因为它可以帮助用户找到他们想要的内容。然而,这个搜索功能又必须快速,高效地获取信息,因为这可能是用户打开您的应用程序的主要原因。 AndroID SDK提供了一组API实现这类功能,在此文中,我们将回顾实现该应用程序所需的第一步。
首先建立一个Empty activity
<menu xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto"> <item androID:ID="@+ID/search" androID:Title="@string/hint_search" androID:icon="@androID:drawable/ic_menu_search" app:showAsAction="collapseActionVIEw|ifRoom" app:actionVIEwClass="androID.support.v7.Widget.SearchVIEw" /></menu>
创建好菜单文件后,我们将加载在MainActivity对象下面,如下所示:
public class MainActivity extends AppCompatActivity implements SearchVIEw.OnqueryTextListener { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); } @OverrIDe public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem searchItem = menu.findItem(R.ID.search); SearchVIEw searchVIEw = (SearchVIEw) MenuItemCompat.getActionVIEw(searchItem); searchVIEw.setonqueryTextListener(this); return true; } @OverrIDe public boolean onqueryTextsubmit(String query) { // User pressed the search button return false; } @OverrIDe public boolean onqueryTextChange(String newText) { // User changed the text return false; }}
用户在搜索栏输入城市名称,显示城市名称列表。这个列表被存储在服务器中。我们要做的第一件事情就是创建一个搜索栏文件res/xml/searchable.xml,如下所示:
<searchable xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:hint="@string/hint_search" androID:label="@string/app_name" androID:voiceSearchMode="showVoiceSearchbutton|launchRecognizer" androID:searchSuggestAuthority="ngvl.androID.demosearch.citysuggestion" androID:searchSuggestIntentAction="androID.intent.action.VIEW" androID:searchSuggestIntentData="content://ngvl.androID.demosearch.city"/>
创建一个新的ContentProvIDer,并将其命名为CitySuggestionProvIDer,只是执行查询():
public class CitySuggestionProvIDer extends ContentProvIDer { List<String> citIEs; @OverrIDe public boolean onCreate() { return false; } @OverrIDe public Cursor query(Uri uri, String projection, String selection, String selectionArgs, String sortOrder) { if (citIEs == null || citIEs.isEmpty()){ OkhttpClIEnt clIEnt = new OkhttpClIEnt(); Request request = new Request.Builder() .url("https://dl.dropBoxusercontent. ... 6quot;) .build(); try { Response response = clIEnt.newCall(request).execute(); String JsonString = response.body().string(); JsONArray JsonArray = new JsONArray(JsonString); citIEs = new ArrayList<>(); int lenght = JsonArray.length(); for (int i = 0; i < lenght; i++) { String city = JsonArray.getString(i); citIEs.add(city); } } catch (Exception e) { e.printstacktrace(); } } MatrixCursor cursor = new MatrixCursor( new String { BaseColumns._ID, SearchManager.SUGGEST_ColUMN_TEXT_1, SearchManager.SUGGEST_ColUMN_INTENT_DATA_ID } ); if (citIEs != null) { String query = uri.getLastPathSegment().toupperCase(); int limit = Integer.parseInt(uri.getqueryParameter(SearchManager.SUGGEST_ParaMETER_liMIT)); int lenght = citIEs.size(); for (int i = 0; i < lenght && cursor.getCount() < limit; i++) { String city = citIEs.get(i); if (city.toupperCase().contains(query)){ cursor.addRow(new Object{ i, city, i }); } } } return cursor; } // Other methods are empty...}
当用户开始输入文字,我们的内容提供者使用下面这样的uri。
content://ngvl.androID.demosearch.citysuggestion/search_suggest_query/santos?limit=50
构建依赖性:
dependencIEs { ... compile 'com.squareup.okhttp3:okhttp:3.0.1'}
一定要在AndroIDManifest.xml添加INTERNET权限和ContentProvIDer声明,如下所示:
<manifest ... <uses-permission androID:name="androID.permission.INTERNET"/> <application... <provIDer androID:name=".CitySuggestionProvIDer" androID:authoritIEs="ngvl.androID.demosearch.citysuggestion" androID:enabled="true" androID:exported="true"/>
之后,我们还需要配置活动与搜索的连接。更改在AndroIDManifest.xml活动的声明:
<activity androID:name=".MainActivity"> <intent-filter> <action androID:name="androID.intent.action.MAIN"/> <category androID:name="androID.intent.category.LAUNCHER"/> </intent-filter> <intent-filter> <action androID:name="androID.intent.action.SEARCH"/> </intent-filter> <Meta-data androID:name="androID.app.searchable" androID:resource="@xml/searchable"/></activity>
将信息传给SearchVIEw Widget
@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem searchItem = menu.findItem(R.ID.search); SearchVIEw searchVIEw = (SearchVIEw) MenuItemCompat.getActionVIEw(searchItem); searchVIEw.setonqueryTextListener(this); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchVIEw.setSearchableInfo(searchManager.getSearchableInfo( new Componentname(this, MainActivity.class))); searchVIEw.setIconifIEdByDefault(false); return true;}
当用户按下搜索按钮或选择列表中的一个名称时,会在MainActivity中创建并显示的新实例。为了避免这种情况,我们可以在Manifest.xml设置Activity的launchMode为singletop AndroID并执行onNewIntent()的方法:
<activity androID:name=".MainActivity" androID:launchMode="singletop">
@OverrIDeprotected voID onNewIntent(Intent intent) { super.onNewIntent(intent); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.query); Toast.makeText(this, "Searching by: "+ query, Toast.LENGTH_SHORT).show(); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { String uri = intent.getDataString(); Toast.makeText(this, "Suggestion: "+ uri, Toast.LENGTH_SHORT).show(); }}
在AndroIDManifest.xml中声明:
<activity androID:name=".SearchableActivity"> <intent-filter> <action androID:name="androID.intent.action.SEARCH" /> </intent-filter> <Meta-data androID:name="androID.app.searchable" androID:resource="@xml/searchable"/></activity>
记得从MainActivity声明中删除这些相同的配置。
@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) { ... searchVIEw.setSearchableInfo(searchManager.getSearchableInfo( new Componentname(this, SearchableActivity.class))); ...}// Remove onNewIntent method too
下面的代码显示在SearchableActivity中如何处理搜索:
public class SearchableActivity extends AppCompatActivity { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_searchable); TextVIEw txt = (TextVIEw)findVIEwByID(R.ID.textVIEw); Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.query); txt.setText("Searching by: "+ query); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { String uri = intent.getDataString(); txt.setText("Suggestion: "+ uri); } }}总结
以上是内存溢出为你收集整理的Android初学者之搜索栏创建全部内容,希望文章能够帮你解决Android初学者之搜索栏创建所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)