2016-10-17 4 views
0

Я новичок в разработке приложений для Android и в настоящее время пытаюсь выяснить, как добавить поиск в приложение. Я сделал некоторые поиски, и учебник, который был самым простым для меня, - here.Изменение Android Search для ListView

Приложение работает и ищет, как должно. Единственная проблема заключается в том, что учебник предназначен для поиска в ListView. В действии, в котором размещен поиск моего приложения, содержатся другие сведения (itemview, textview), которые должны быть на экране, поэтому ListView не будет работать для того, что я пытаюсь сделать. Как изменить этот пример, чтобы предоставить раскрывающийся список предложений, когда пользователь вводит в поле поиска? В идеале, мне бы хотелось, чтобы поиск был найден в этом image here.

ItemSearch.java

import android.app.SearchManager; 
import android.content.Context; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.SearchView; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

import java.util.List; 

public class ItemSearch extends AppCompatActivity { 

    ArrayAdapter<String> adapter; 

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

     final String[] months = {"January", "February", "March", "April", 
       "May", "June", "July", "August", "September", "October", 
       "November", "December"}; 
     adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, months); 
     final ListView listview = (ListView) findViewById(R.id.listView1); 
     listview.setAdapter(adapter); 

     listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
       String text = (String) listview.getItemAtPosition(position); 
       Toast.makeText(getApplicationContext(), text, 
         Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.menu_search, menu); 


     SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); 

     searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 
     searchView.setIconifiedByDefault(false); 
     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
      @Override 
      public boolean onQueryTextSubmit(String query) { 
       return false; 
      } 

      @Override 
      public boolean onQueryTextChange(String newText) { 

       adapter.getFilter().filter(newText); 

       return false; 
      } 
     }); 
     return true; 
    } 

} 

item_search_acitivity.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:fillViewport="true"> 
<RelativeLayout 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/item_view_activity" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.me.ItemSearch"> 


    <ImageView 
     /> 

    <ImageView 
     /> 

    <ImageView 
     /> 

    <TextView 
     /> 

    <TextView 
     /> 

    <TextView 
     /> 

    <ListView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/listView1" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 
</RelativeLayout> 
    </ScrollView> 

menu_search.xml под Рез/меню/menu_search

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <item android:id="@+id/search" 
      android:title="@string/hint_search" 
      android:icon="@android:drawable/ic_menu_search" 
      app:showAsAction="collapseActionView|ifRoom" 
      app:actionViewClass="android.support.v7.widget.SearchView" /> 
</menu> 

searchable.xml под Рез/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/search_hint" 
    android:searchSuggestIntentAction="android.intent.action.VIEW"> 
</searchable> 

В AndroidManifest.xml я добавил

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

Я предполагаю, что вы уже пробовали https://androidhub.intel.com/en/posts/nglauber/Android_Search.html – zombie

+0

@zombie да, у меня есть. Любые предложения о том, как объединить эти два без класса CitySuggestionProvider.java? Я бы просто хотел, чтобы приложение искало массив строк String выше. – cb92

ответ

0

Для этого типа функциональности выпадающий внушения вы бы использовать AutoCompleteTextView.

Пример использования ниже:

В файле макета:

<AutoCompleteTextView 
    android:id="@+id/auto_complete_tv" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/key"/> 

В файле ресурсов, таких как arrays.xml или strings.xml:

<string-array name="suggestions"> 
    <item>January</item> 
    <item>February</item> 
    <item>March</item> 
    ... 
</string-array> 

В вашем фрагменте или деятельности:

AutoCompleteTextView autoCompleteTv; 

... 

AutoCompleteTextView autoCompleteTv = (AutoCompleteTextView) view.findViewById(R.id.auto_complete_tv); 
autoCompleteTv.setAdapter(ArrayAdapter.createFromResource(view.getContext(), R.array.suggestions, android.R.layout.simple_dropdown_item_1line)); 
Смежные вопросы