Global “search function” in whole app

∥☆過路亽.° 提交于 2019-12-21 16:20:26

问题


In my application throughout I want the search button to perform a separate Activity. i.e. From anywhere in the app when I press the search button I want a separate Activity to get called.

Is there any way that instead of defining onSearchRequested() in every activity, I just configure it at one place (like Manifest.xml) and it can be used throughout the app?


回答1:


You could define an (not necessarily) abstract class that extends Activity, implement onSearchRequest there and inherit all other Activity classes from that class. In this way you only have to define the onSearch behaviour only once.

i.e.

public abstract class MyBaseActivity extends Activity {
    @Override
    public void onSearchRequest() {
       // Your stuff here
    }
}

public class MyActivity1 extends MyBaseActivity {
   // OnSearchRequest is already implemented
}

If you plan to use multiple subclasses of Activity, i.e. ListActivity, this might not be a good solution, as you have to create a abstract base class for all Activity subclasses you use. In this case I'd recommend creating an additional class, encapsulating the search button handling code and call that from you activities onSearchRequest, i.e.

public class SearchButtonHandle {
    public void handleSearch(Context c) {
       // Your search btn handling code goes here
    }  
}

public class MyActivity1 extends Activity {  // Or ListActivity ....
    @Override
    public void onSearchRequest() {
       new SearchButtonHandle().handleSearch(this);
    }
}

Of course you can also combine both approches by defining an Abstract Subclass of all Activity Subclasses you use and implement the onSearchRequest as in the example above with an external Search Handler



来源:https://stackoverflow.com/questions/11592552/global-search-function-in-whole-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!