首页 > 为什么SearchView提交搜索后onNewIntent()没被调用到?

为什么SearchView提交搜索后onNewIntent()没被调用到?

我已经在manifest里面设置好了,可是按下搜索按键后就是不会调用onNewIntent方法,这是咋回事?照理说设置了android:lauchMode后就会调用这个方法了的。
我的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.leu.myapplication" >

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity"
            android:launchMode="singleTop">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

下面是我demo的源码,是一个使用SearchView的demo。
理想按下搜索键后应该显示一个输入文字的Toast
https://github.com/Leu-Z/MyApplication2


设置singleInstance试试


根据API说明,你的问题的关键在于onQueryTextSubmit()的返回值:只有返回false,才能使SearchView发起一个intent。如果返回true,就认为这个submit已经被listener自己处理掉了。
修改返回值为fasle,解决问题。已经测试通过 :)

public abstract boolean onQueryTextSubmit (String query)
Added in API level 11
Called when the user submits the query. This could be due to a key press on the keyboard or due to pressing a submit button. The listener can override the standard behavior by returning true to indicate that it has handled the submit request. Otherwise return false to let the SearchView handle the submission by launching any associated intent.

我把你的代码也贴出来了,供其他人参考。

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    /*
     * 输入完成后,提交时触发的方法,一般情况是点击输入法中的搜索按钮才会触发。表示现在正式提交了
     *
     * @param queryText
     *
     * @return true to indicate that it has handled the submit request.
     * Otherwise return false to let the SearchView handle the
     * submission by launching any associated intent.
     */
    @Override
    public boolean onQueryTextSubmit(String queryText) {
        if (searchView != null) {
            // 得到输入管理对象
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 这将让键盘在所有的情况下都被隐藏,但是一般我们在点击搜索按钮后,输入法都会乖乖的自动隐藏的。
                // 输入法如果是显示状态,那么就隐藏输入法
                imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
            }
            // 不获取焦点
            searchView.clearFocus();
            Log.d(TAG, "onQueryTextSubmit = " + queryText);
        }
        // 修改为false,你看,你自己的代码注释里,已经对返回值做了说明呀!!!
        return false;
    }
});
【热门文章】
【热门文章】