[英]Android using Fragment instead of activity for a library
I am using this library MaterialSearchView in my app for implementing Gmail like search view. 我在我的应用程序中使用此库MaterialSearchView来实现Gmail(例如搜索视图)。 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. 除了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: 上面代码中的mContext
在构造函数中设置为:
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
. mContext
可能不是Activity
。
Try using this logic (copied from MediaRouteButton.getActivity() ) to get the Activity
. 尝试使用此逻辑(从MediaRouteButton.getActivity()复制)来获取Activity
。
Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.