Поиск с помощью Android: кнопка поиска не вызывает поисковую активность (другие решения не помогли)

Я написал это небольшое тестовое приложение, чтобы продемонстрировать проблему, то есть поиск не запускается, когда пользователь нажимает кнопку поиска на клавиатуре.

Я следовал руководствам для разработчиков, но из моего веб-поиска выяснилось, что в официальном руководстве для разработчиков не хватает некоторых моментов. Из моего SO поиска (который не помог):

  • Ссылка 1: Решено путем добавления тега в элемент в манифесте. Я также посмотрел манифест образца "Словарь пользователя" (я не знаю, где я могу найти образцы в Интернете, или я бы дал ссылку на него). Этот тег есть в элементе приложения.

  • Ссылка 2: "android:label" и "android:hint" в res/xml/searchable.xml должны быть ссылками на строковые ресурсы, а не жестко закодированными строками. Мои есть.

  • Ссылка 3: Добавьте тег с "android:name="android.app.default_searchable" " (и "android: value ="<. Searchable-Activity-name>"") в манифесте в действии, из которого выполняется поиск. будет инициировано. Пробовал это, похоже, не работает.

  • Ссылка 4: "Ваша поисковая активность должна что-то делать - и отображать результаты". Мой делает, он получает намерение с действием ACTION_SEARCH и передает строку поискового запроса, извлеченную из намерения, в метод с именем "executeSearch (string)", который отображает строку в текстовом представлении.

Так что я делаю не так, и что я могу сделать, чтобы решить эту проблему?

Код: MainActivity.java - имеет один SearchView - пользователь вводит запрос и нажимает кнопку поиска на клавиатуре.

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

TestTwoActivity.java

    public class TestTwoActivity extends Activity {
        TextView tv;
        private static final String TAG = TestTwoActivity.class.getSimpleName();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_test_two);

            /**
             * The following code enables assisted search on the SearchView by calling setSearchableInfo() and passing it our SearchableInfo object.
             */
            SearchView searchView = (SearchView) findViewById(R.id.searchActivity_searchView);
            // SearchManager => provides access to the system search services.

            // Context.getSystemService() => Return the handle to a system-level
            // service by name. The class of the returned object varies by the
            // requested name.

            // Context.SEARCH_SERVICE => Returns a SearchManager for handling search

            // Context = Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android
            // system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching
            // activities, broadcasting and receiving intents, etc.

            // Activity.getComponentName = Returns a complete component name for this Activity 

            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

            /**
             * If the search is executed from another activity, the query is sent to this (searchable) activity in an Intent with ACTION_SEARCH action.
             */
            // getIntent() Returns the intent that started this Activity
            Intent intent = getIntent();
            if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
                Log.i(TAG, "Search Query Delivered");//check
                String searchQuery = intent.getStringExtra(SearchManager.QUERY);
                performSearch(searchQuery);
            }

        }

        private void performSearch(String searchQuery) {
            //Just for testing purposes, I am simply printing the search query delivered to this searchable activity in a textview.
            tv = (TextView) findViewById(R.id.testTwoActivity_textView);
            tv.setText(searchQuery);
        }
}

res/xml/searchable.xml - конфигурация с возможностью поиска

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/searchViewHint" >
</searchable>

Файл манифеста

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tests"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".TestTwoActivity"
            android:label="@string/title_activity_test_two" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH"/> <!-- Declares the activity to accept ACTION_SEARCH intent -->
            </intent-filter> 
                <meta-data 
                    android:name="android.app.searchable"
                    android:resource="@xml/searchable" /> <!-- Specifies the searchable configuration to use --> 
        </activity>

        <!-- Points to searchable activity so the whole app can invoke search. -->
        <meta-data android:name="android.app.default_searchable"
                   android:value=".TestTwoActivity" />

    </application>

</manifest>

Макеты:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.tests.MainActivity" >

    <android.support.v7.widget.SearchView
        android:id="@+id/searchActivity_searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         /> 

</LinearLayout>

activity_test_two.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="${relativePackage}.${activityClass}" >

    <android.support.v7.widget.SearchView
        android:id="@+id/searchActivity_searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         /> 

    <TextView
        android:id="@+id/testTwoActivity_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

РЕДАКТИРОВАТЬ 1: это безумие, что я написал похожее приложение с поисковым дилогом вместо поискового виджета, который отлично работает.

Я попытался отладить его в Eclipse, но отладка останавливается, потому что TestTwoActivity (поиск активности) просто не начнется.

1 ответ

Решение

Я не уверен, что вы забыли добавить его, но ваш MainActivity пропускает настройку поиска информации на SearchView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SearchView searchView = (SearchView) findViewById(R.id.searchActivity_searchView);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}

Как примечание стороны:

У меня были проблемы с default_searchable метатег, при использовании ароматов. Казалось, он работает только при использовании полного пути (пропуская аромат) к поисковой деятельности, например:

<meta-data 
    android:name="android.app.default_searchable"
    android:value="com.example.SearchActivity"/>
Другие вопросы по тегам