【发布时间】:2016-04-06 06:25:19
【问题描述】:
我知道这是一个常见问题。
但是,除非用户提交查询,否则每当用户点击 searchView(而不是图标)时启动另一个活动是无效的。
以下是功能代码,每当用户提交查询时,它就会启动另一个活动,但是,我想在用户单击 searchView(展开的文本字段)后立即启动另一个活动。
提前致谢。
xml
<activity
android:name=".MainPage"
android:label="@string/title_activity_main_page"
android:theme="@style/AppThemeMain">
<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=".SearchActivity" >
</meta-data>
</activity>
<provider android:name=".MySuggestionProvider"
android:authorities="ad.aureus.apicius.MySuggestionProvider" />
<activity android:name=".SearchActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
MainPage.class
@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_page, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));
return true;
}
顺便说一句,我尝试过在 onOptionsItemSelected 方法中编写 if/switch 语句来识别 searchView id,然后使用 Intents。两者都不起作用。
onCreate 方法:
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
对于最近的查询建议,我在 onCreate 中确实有这个,我不确定这是否是我的问题的原因。我假设,因为这是最初调用的,它会抑制 onOptionsItemSelected 方法的属性?不确定..
这是菜单的 xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item android:id="@+id/search"
android:title="@string/title_activity_main_page"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
【问题讨论】:
-
尝试在 setOnQueryTextListener 上使用 SearchView 并在此 onQueryTextChange 内部检查长度是否等于 0,然后转移到另一个活动试试这个并告诉我
-
为你的视图添加一个监听器
-
所以你想开始另一个活动,当用户只是点击一个 SearchView,不输入里面的任何文本?为什么?干什么用的?
-
你为什么不直接使用 searchView.setOnClickListener();?
-
这是因为我对这两个活动有不同的目的,主要是因为搜索小部件仅用于显示,直到用户点击它。
标签: android android-studio searchview