Global search function in the whole application

In my application, in all cases, I want the search button to execute a separate Activity . that is, from anywhere in the application, when I click the search button, I want a separate operation to be called for the call.

Is there a way that instead of defining onSearchRequested() in each action, I just configure it in one place (for example, Manifest.xml ) and it can be used throughout the application?

+5
source share
1 answer

You can define (optionally) an abstract class that extends Activity, implements onSearchRequest, and inherits all other Activity classes from this class. Therefore, you should only define onSearch behavior 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 several subclasses of Activity, i.e. ListActivity, this may not be a good solution, since you need to create an abstract base class for all Activity subclasses that you use. In this case, I would recommend creating an additional class by encapsulating the search button processing code and calling it from your onSearchRequest actions, 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 approaches by defining an abstract subclass of all activity subclasses that you use and implement onSearchRequest, as in the example above, using an external search handler

+6
source

Source: https://habr.com/ru/post/921964/


All Articles