在操作栏中实现SearchView
我需要从我的arrayList<String>
创buildSearchView
,并在下拉列表中显示与此相同的build议
我寻找教程一步一步解释如何在一个操作栏中build立一个SearchView
。
我已经阅读了文档,并遵循谷歌的例子,但它对我没有用。
我已经创build了search
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_search" android:title="Search" android:icon="@android:drawable/ic_menu_search" android:showAsAction="always" android:actionViewClass="android.widget.SearchView" /> </menu>`
但是我不知道如何设置string数组的参数。 我试图在不同的Activity中检索结果,但不工作。
花了一段时间才为这个解决scheme,但发现这是以你描述的方式让它工作的最简单的方法。 可以有更好的方法来做到这一点,但由于你没有发布你的活动代码,我将不得不临时凑合,并假设你在活动开始时有一个这样的列表:
private List<String> items = db.getItems();
ExampleActivity.java
private List<String> items; private Menu menu; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.example, menu); this.menu = menu; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView search = (SearchView) menu.findItem(R.id.search).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); search.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextChange(String query) { loadHistory(query); return true; } }); } return true; } // History @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void loadHistory(String query) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Cursor String[] columns = new String[] { "_id", "text" }; Object[] temp = new Object[] { 0, "default" }; MatrixCursor cursor = new MatrixCursor(columns); for(int i = 0; i < items.size(); i++) { temp[0] = i; temp[1] = items.get(i);replaced s with i as s not used anywhere. cursor.addRow(temp); } // SearchView SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView(); search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items)); } }
现在您需要创build一个从CursorAdapter
扩展的适配器:
ExampleAdapter.java
public class ExampleAdapter extends CursorAdapter { private List<String> items; private TextView text; public ExampleAdapter(Context context, Cursor cursor, List<String> items) { super(context, cursor, false); this.items = items; } @Override public void bindView(View view, Context context, Cursor cursor) { text.setText(items.get(cursor.getPosition())); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.item, parent, false); text = (TextView) view.findViewById(R.id.text); return view; } }
更好的方法是,如果列表数据来自数据库,则可以将数据库函数返回的Cursor
直接传递给ExampleAdapter
并使用相关的列select器在适配器中引用的TextView
显示列文本。
请注意:导入CursorAdapter
不要导入Android支持版本,而是导入标准的android.widget.CursorAdapter
。
该适配器还将需要一个自定义布局:
RES /布局/ item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/item" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
您现在可以通过向布局添加其他文本或图像视图并使用适配器中的数据填充它们来自定义列表项目。
这应该是所有的,但如果你还没有这样做,你需要一个SearchView的菜单项:
RES /菜单/的example.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/search" android:title="@string/search" android:showAsAction="ifRoom" android:actionViewClass="android.widget.SearchView" /> </menu>
然后创build一个可search的configuration:
RES / XML / searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/search" android:hint="@string/search" > </searchable>
最后,在清单文件中的相关活动标签内添加:
AndroidManifest.xml中
<intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.default_searchable" android:value="com.example.ExampleActivity" /> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
请注意:示例中使用的@string/search
string应该在values / strings.xml中定义,也不要忘记为您的项目更新对com.example
的引用。
如果其他人在searchviewvariables上有一个nullptr,我发现这个项目的设置有点不同:
旧:
android:showAsAction="ifRoom" android:actionViewClass="android.widget.SearchView"
新:
app:showAsAction="ifRoom|collapseActionView" app:actionViewClass="android.support.v7.widget.SearchView"
有关更多信息,它的更新文档位于此处 。
*** For serachview use these code --------------- 1. For XML <android.support.v7.widget.SearchView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/searchView"> </android.support.v7.widget.SearchView> *** 2. In your Fragment or Activity package com.example.user.salaryin; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.user.salaryin.Adapter.BusinessModuleAdapter; import com.example.user.salaryin.Network.ApiClient; import com.example.user.salaryin.POJO.ProductDetailPojo; import com.example.user.salaryin.Service.ServiceAPI; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by USer on 24-08-2017. */ public class OneFragment extends Fragment implements SearchView.OnQueryTextListener { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; ArrayList<ProductDetailPojo> arrayList; BusinessModuleAdapter adapter; private ProgressDialog pDialog; GridLayoutManager gridLayoutManager; SearchView searchView; public OneFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.one_fragment,container,false); pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Please wait..."); searchView=(SearchView)rootView.findViewById(R.id.searchView); searchView.setQueryHint("Search BY Brand"); searchView.setOnQueryTextListener(this); recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); layoutManager = new LinearLayoutManager(this.getActivity()); recyclerView.setLayoutManager(layoutManager); gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setHasFixedSize(true); getImageData(); // Inflate the layout for this fragment //return inflater.inflate(R.layout.one_fragment, container, false); return rootView; } private void getImageData() { pDialog.show(); ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class); Call<List<ProductDetailPojo>> call = service.getBusinessImage(); call.enqueue(new Callback<List<ProductDetailPojo>>() { @Override public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) { if (response.isSuccessful()) { arrayList = (ArrayList<ProductDetailPojo>) response.body(); adapter = new BusinessModuleAdapter(arrayList, getActivity()); recyclerView.setAdapter(adapter); pDialog.dismiss(); } else if (response.code() == 401) { pDialog.dismiss(); Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) { Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show(); pDialog.dismiss(); } }); } /* @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem menuItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); searchView.setQueryHint("Search Product"); searchView.setOnQueryTextListener(this); }*/ @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { newText = newText.toLowerCase(); ArrayList<ProductDetailPojo> newList = new ArrayList<>(); for (ProductDetailPojo productDetailPojo : arrayList) { String name = productDetailPojo.getDetails().toLowerCase(); if (name.contains(newText) ) newList.add(productDetailPojo); } adapter.setFilter(newList); return true; } } 3. In adapter class public void setFilter(List<ProductDetailPojo> newList){ arrayList=new ArrayList<>(); arrayList.addAll(newList); notifyDataSetChanged(); }