Home > Back-end >  How to make a SearchView inside MaterialToolbar using menu item
How to make a SearchView inside MaterialToolbar using menu item

Time:10-05

Good day sirs/maams. I am asking for your help. I want to implement a SearchView out of a menu item inside my MaterialToolbar.

Here's my code:

activity_main.xml

<com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <com.google.android.material.appbar.MaterialToolbar
                android:id="@ id/nav_drawer"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@drawable/main_bg"
                android:theme="@style/CustomSearchView"
                app:title="Dashboard"
                app:titleTextColor="@color/white"
                app:navigationIcon="@drawable/ic_menu_24"
                app:menu="@menu/top_app_bar"
                style="@style/MaterialToolbar"/>
        </com.google.android.material.appbar.AppBarLayout>

menu.xml

<?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/top_nav_search"
        android:icon="@drawable/ic_search_24"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"/>

</menu>

MainActivity.xml

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.top_app_bar, menu)

        val searchItem = menu?.findItem(R.id.top_nav_search)


        if(searchItem != null){
            val searchView = searchItem.actionView as SearchView
            searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
                override fun onQueryTextSubmit(query: String?): Boolean {

                    //show submitted text for testing purposes.
                    Toast.makeText(this@MainActivity, "Looking for $query", Toast.LENGTH_SHORT).show()
                    return true
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    return true
                }

            })
        }
        return super.onCreateOptionsMenu(menu)
    }

The result is whenever I try to submit a text, the toast message does not appear. It seems that my code doesn't work. Thank you and have a nice day.

CodePudding user response:

I have managed like this Globle variable

 private lateinit var searchView: SearchView

You can do the same

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search_filter_menu, menu)
        searchView = menu.findItem(R.id.search).actionView as SearchView
        searchView.queryHint = getString(R.string.search_student_txt)
        searchView.maxWidth = Int.MAX_VALUE
        searchView.findViewById<View>(androidx.appcompat.R.id.search_plate)
            .setBackgroundColor(Color.TRANSPARENT)
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(s: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(s: String?): Boolean {
                searchText(s)
                return true
            }
        })
        return super.onCreateOptionsMenu(menu)
    }

CodePudding user response:

You are adding a menu programmatically so no need to define it in activity_mian.xml again. You are setting the listener to different SearchView that you see on the screen. That is the reason that toast is not displaying on submit. Simply remove the ToolBar from your activity_main, then it should work.

Make sure you are adding ActionBar Theme in styles:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!-- Customize your theme here. -->
 </style>

And add it in the Manifest file:

<activity android:name=".MainActivity"
            android:theme="@style/AppTheme">

OR

Simply, why can't we add the search view directly in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include layout="@layout/custom_toolbar" />

    <!--Remaining activity UI goes here-->


</LinearLayout>

custom_toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/mToolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:elevation="6dp"
    android:translationZ="6dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="5dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <androidx.appcompat.widget.SearchView
            android:id="@ id/searchView"
            android:layout_alignParentEnd="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:queryHint="Search" />

    </RelativeLayout>


</androidx.appcompat.widget.Toolbar>

Then use it in your MainActivity under onCreate()

import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.custom_toolbar.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                if (!query.isNullOrEmpty()) {
                    Toast.makeText(this@MainActivity, "Looking for $query", Toast.LENGTH_SHORT)
                        .show()
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return false
            }
        })
    }
}
  • Related