I am using this library MaterialSearchView in my app for implementing Gmail like search view. The library has provided the implementation details using an Activity. I tried the code inside a fragment, making the necessary changes.
To implement it we do something like this from an activity:
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
But, I am using a fragment instead so what I do is:
searchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);
Everything works fine except the VoiceSearch. The library implements voice search using the following code:
private void onVoiceClicked() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak an item name or number"); // user hint
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); // setting recognition model, optimized for short phrases – search queries
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); // quantity of results we want to receive
if (mContext instanceof Activity) {
((Activity) mContext).startActivityForResult(intent, REQUEST_VOICE);
}
How can I make this work? mContext
in the above code is set inside the constructor as:
public MaterialSearchView(Context context) {
this(context, null);
}
How can I make it work from a fragment? Code for the library
mContext
might not be an Activity
.
Try using this logic (copied from MediaRouteButton.getActivity() ) to get the Activity
.
Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.