I have implemented SearchView in MaterialToolBar in my project. Everything working fine except for the final step. When I type anything in the search bar and click on the keyboard find button, it doesn't show anything. Please help.
Video of my problem https://drive.google.com/file/d/1GpE16D3drLGYp0ZetHgNlT8s7qZSFuWk/view?usp=drivesdk
Menu.xml
<item
android:id="@+id/menu_search"
android:title="@string/search"
android:icon="@drawable/ic_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
activity.xml
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/category1_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingEnd="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="@color/dark_blue"
app:menu="@menu/cart_share"
tools:ignore="RtlSymmetry">
<ImageView
android:id="@+id/img_back_all_category"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:contentDescription="TODO"
android:src="@drawable/ic_keyboard_arrow_left" />
<TextView
android:id="@+id/tv_all_categories"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/product_name"
android:fontFamily="@font/montserrat"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="@color/white"
android:layout_marginStart="25sp"/>
</com.google.android.material.appbar.MaterialToolbar>
java code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.cart_search_menu, menu);
MenuItem menuItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Type here to search");
searchView.setMaxWidth(android.R.attr.width);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//getSearchResults(query); Also tried
getSearchResults(searchView.getQuery().toString());
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
menuItem.collapseActionView();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
I changed the sequence of code lines after that it worked fine.
Before:
super.onCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.category1_toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_product_list);
After:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
Toolbar toolbar = findViewById(R.id.category1_toolbar);
setSupportActionBar(toolbar);