Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SearchView using FloatingActionButton

Tags:

java

android

I am trying to implement a search in an Android App but unfortunately I don't find a way of implementing a SearchView without a MenuItem. Like it's done here in onCreateOptionsMenu():

SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView addView =
                (SearchView) menu.findItem(R.id.action_add).getActionView();
addView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

I would like to implement the SearchView using FloatingActionButton but sadly casting doesn't work altough getActionView() above also returns a View. I tried it like this:

SearchView searchView = (SearchView) floatingActionButton;

but sadly I got:

java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.SearchView

Here's my menu declaration:

<item
        android:id="@+id/action_add"
        android:icon="@drawable/ic_add"
        android:title="Add"
        app:showAsAction="collapseActionView|always"
        android:actionViewClass="android.widget.SearchView"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />

Here's my manifest declaration:

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
        >
            <meta-data android:name="android.app.default_searchable"
                android:value=".SearchResultsActivity" />


        </activity>
        <activity
            android:name=".SearchResultsActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme"
            android:launchMode="singleTop">

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
        </activity>

How can I get the FloatingActionButton to trigger the search widget in the android toolbar? Thanks for your help.

like image 644
czer Avatar asked Mar 04 '26 06:03

czer


1 Answers

Try with MenuItemCompat.expandActionView(yourSearchMenuItem); That should work also for API < 14 as far I recall.

like image 199
Aitor Viana Avatar answered Mar 06 '26 19:03

Aitor Viana