5

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?

Michal
  • 15,429
  • 10
  • 73
  • 104
reiley
  • 3,759
  • 12
  • 58
  • 114

1 Answers1

6

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

Hans Hohenfeld
  • 1,729
  • 11
  • 14
  • That is actually a great idea, but what if he wants to use ListView activity somewhere? – Michal Jul 21 '12 at 13:28
  • 1
    @Michal I guess in that case it depends, If he uses multiple ListActivities or other subclasses of Activity, composition might be a better solution than inheritance. He could for example create a Search Handling class encapsulating the code for handling the search button and call taht from all activities. I'll edit my answer to point that out with an example – Hans Hohenfeld Jul 21 '12 at 13:43