I have a searchView in my IndexActivity. On clicking the searchView a new activity is started called SearchActivity.
Inside the search activity again, I have the searchView which expands on clicking. It has a query listener which does an external API call.
However, after I open the SearchActivity by clicking on searchView icon, I have to again click on searchView to type in it. What I want is searchView should be focussed as soon as the activity starts.
This is my code of searchactivity:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_search, menu)
val searchView: SearchView =
menu?.findItem(R.id.menu_search)?.actionView as SearchView
// searchView.setIconifiedByDefault(false)
// searchView.focusable = View.FOCUSABLE
// searchView.isIconified = false
// searchView.requestFocusFromTouch()
// searchView.onActionViewExpanded()
The commented lines are the ones I tried by searching on the web but it doesn't seem to work.
This is my code in toolbar_searchbar.xml which is included in activity_search set by SearchActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleTextColor="@color/cardview_light_background"
app:subtitleTextAppearance="@font/alegreya_sans_medium"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@android:color/transparent"
android:id="@+id/toolbar_searchbar"
app:popupTheme="@style/AppTheme.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is the code of toolbar_search.xml which is inflated as seen in the code provided above:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:title="Search"
android:id="@+id/menu_search"
android:icon="@drawable/quantum_ic_search_grey600_24"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
/>
</menu>
This is what I get at the start.
This is what I want at the start.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…