I want to open a new activity whenever the search icon
is clicked on the mainactivity
. This new activity called SearchableActivity
will handle all the relevant search results in the listview
. I have followed the steps described in this post.
This is what I currently have:
I want to open up the SearchableActivity
when the user enters into SearchView
.
Here is what my code looks like:
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:launchMode="singleTop">
<!-- meta tag points to the activity which displays the results -->
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchableActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SearchableActivity"
android:parentActivityName=".MainActivity">
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
<!-- meta tag and intent filter go into results activity -->
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
MainActivity
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.options_menu, menu)
val manager = getSystemService(SEARCH_SERVICE) as SearchManager
(menu?.findItem(R.id.search)?.actionView as SearchView).apply {
setSearchableInfo(manager.getSearchableInfo(ComponentName(this.context, SearchableActivity::class.java)))
}
return true
}
SearchableActivity
class SearchableActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_searchable)
Toast.makeText(this@SearchableActivity, "SA created", Toast.LENGTH_LONG).show()
handleIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent !== null)
handleIntent(intent)
}
private fun handleIntent(intent: Intent) {
if (Intent.ACTION_SEARCH == intent.action) {
val query = intent.getStringExtra(SearchManager.QUERY)
Toast.makeText(this@SearchableActivity, "QUERY: $query", Toast.LENGTH_LONG).show()
}
}
}