android-SearchView无意启动可搜索活动
作者:互联网
我正在使用SearchView来启动一个显示搜索结果的新活动.我遵循以下来源:
> Android教程:Creating a Search Interface
>因此:Start new activity from SearchView
>因此:Cannot get searchview in actionbar to work
新的可搜索活动ListActivity是从MainActivity的应用栏中的SearchView小部件启动的.新的可搜索活动已启动,但是缺少搜索意图(从不调用onNewIntent方法).
Searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_label"
android:hint="@string/search_hint" >
</searchable>
AndroidManifest.xml
<application
...
<meta-data
android:name="android.app.default_searchable"
android:value=".ui.ListActivity" />
<activity
android:name=".ui.MainActivity"
...
</activity>
<activity
android:name=".ui.ListActivity"
android:launchMode="singleTop"
...
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
</application>
主要活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// setSupportActionBar
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
return true;
}
}
ListActivity
public class ListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate invoked"); //Log Printed
...
}
@Override
protected void onNewIntent(Intent intent) {
Log.d(TAG, "onNewIntent invoked"); //Log NOT Printed
}
}
考虑到我也用新的ComponentName(this,ListActivity.class)替换了getComponentName(),但是得到了相同的结果:没有错误,没有意图查询.
解决方法:
按照onNewIntent()’s documentation:
This is called for activities that set launchMode to “singleTop” in their package, or if a client used the 07001 flag when calling 07002. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
singleTop仅在活动(在您的情况下为ListActivity)位于顶部的情况下才适用-代替创建新实例,它将重用现有的实例.但是,如果仅从MainActivity中进行搜索(在搜索后返回ListActivity),则将销毁ListActivity实例,然后创建一个新实例-导致调用onCreate(),而不是onNewIntent().
标签:android-intent,searchview,android 来源: https://codeday.me/bug/20191027/1943860.html