Search code examples
javaandroidsearchview

Android - Make whole search view clickable with query hint


So i've been working on this inventory management system in Android Studio. In the fragment for Product Taking i have a search view and i want to make this search views whole body to be clickable. Part of this problem is solved here: Android - Make whole search bar clickable. But i want the search view to have a visible query hint. So basically i want it to be a button with search icon and a text. I want that because it is supposed to open a dialog where the user actually going to search for products. Not from this search view.

When i add the setIconified(true) whole body is clickable but query hint is not visible. Like this:

enter image description here

When i add setIconified(false) query hint is visible but only search icon is clickable. Like this:

enter image description here


Solution

  • You can intercept all touches before SearchView consume them. I've created a simple class that intercept all touch events. Kotlin:

    class TouchInterceptorLayout @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : FrameLayout(context, attrs, defStyleAttr) {
    
        // You need override this method.
        override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
            return true
        }
    }
    

    Java:

    public class TouchInterceptorLayout extends FrameLayout {
        public TouchInterceptorLayout(Context context) {
            super(context);
        }
    
        public TouchInterceptorLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public TouchInterceptorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return true;
        }
    }
    

    See how xml looks:

    <com.example.testci.temp.TouchInterceptorLayout
                android:id="@+id/interceptorLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
    
            <SearchView
                    android:id="@+id/searchView"
                    android:queryHint="@string/app_name"
                    android:iconifiedByDefault="false"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"/>
    </com.example.testci.temp.TouchInterceptorLayout>
    

    Now you need just set OnClickListener to interceptorLayout.

    Full code with my experiment you can find here.