Is it possible to search within Fragments?
I have an Android application that we are porting over to Honeycomb/Android 3.0 and we are using Fragment
s in our new interface.
I have search wor开发者_如何学Cking via the widget as shown here.
The problem is, the widget doesn't pop up any more when using Fragment
s. So the question is how do I get search to be used with Fragment
s?
Or how can I replace this line to be used with Fragment
s?
getActivity().onSearchRequested();
I solved this problem using interface/callbacks.
In my MainActivity
, I write a callback interface:
private SearchRequestedCallback mSearchRequestedCallback;
public void setSearchRequestedCallback(SearchRequestedCallback callback) {
mSearchRequestedCallback = callback;
}
public interface SearchRequestedCallback {
void onSearchRequested();
}
In my Fragment
, I set the callback in the onStart()
and unset it in the onStop()
:
@Override
public void onStart() {
super.onStart();
getActivity().setTitle(getResources().getString(R.string.app_name));
((MainActivity)getActivity()).setSearchRequestedCallback(new SearchRequestedCallback() {
@Override
public void onSearchRequested() {
addFilter();
}
});
}
@Override
public void onStop() {
((MainActivity)getActivity()).setSearchRequestedCallback(null);
super.onStop();
}
You can't. The SearchManager
is implemented to work with Activity
s, not Fragment
s. See this post for more information.
精彩评论