问题
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