How to Create search button in android -
i newbie in android developement. want create search function in comic this:
how can those:
- when click search button, displays input text box.
- when input, displays list of matched items.
you need activity marked searchable. first add meta , intent filter manifest on activity marked single-top.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="..."> <application android:name="..." android:icon="@drawable/logo" android:label="@string/app_name" android:theme="@style/..."> <activity android:name=".mainactivity" android:label="@string/app_name" android:launchmode="singletop" android:theme="@style/apptheme"> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> <intent-filter> <action android:name="android.intent.action.search" /> </intent-filter> ... </activity> ... </application>
then add search view menu xml
<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:orderincategory="500" android:icon="@android:drawable/ic_menu_search" app:showasaction="collapseactionview|ifroom" app:actionviewclass="android.support.v7.widget.searchview" /> ... </menu>
then make activity set search view
@override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_main, menu); searchmanager searchmanager = (searchmanager) getsystemservice(context.search_service); searchview searchview = (searchview) menu.finditem(r.id.search).getactionview(); if (searchview != null) { searchview.setsearchableinfo(searchmanager.getsearchableinfo(getcomponentname())); searchview.setoncloselistener(new searchview.oncloselistener() { @override public boolean onclose() { //todo: reset views return false; } }); searchview.setonquerytextlistener(new searchview.onquerytextlistener() { @override public boolean onquerytextsubmit(string s) { return false; //do default } @override public boolean onquerytextchange(string s) { //note: doing here optional, onnewintent important bit if (s.length() > 1) { //2 chars or more //todo: filter/return results } else if (s.length() == 0) { //todo: reset displayed data } return false; } }); } } return true; }
then make sure activity responds search intent
@override protected void onnewintent(intent intent) { super.onnewintent(intent); if (intent.action_search.equals(intent.getaction())) { final string query = intent.getstringextra(searchmanager.query); //todo: filtering / set results } }
Comments
Post a Comment