【问题标题】:Android using Fragment instead of activity for a libraryAndroid 使用 Fragment 而不是库的活动
【发布时间】:2016-04-11 00:20:23
【问题描述】:

我在我的应用程序中使用这个库 MaterialSearchView 来实现 Gmail 之类的搜索视图。该库使用 Activity 提供了实现细节。我尝试了片段中的代码,进行了必要的更改。

为了实现它,我们从一个活动中做这样的事情:

MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);

但是,我使用的是片段,所以我要做的是:

searchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);

除 VoiceSearch 外,一切正常。该库使用以下代码实现语音搜索:

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);
    }

我怎样才能做到这一点?上面代码中的mContext在构造函数内部设置为:

public MaterialSearchView(Context context) {
    this(context, null);
}

我怎样才能让它从片段中工作? library的代码

【问题讨论】:

  • 究竟是什么不起作用?
  • 它不会启动处理语音动作的活动,在 onVoiceClicked() 中

标签: java android-fragments android-activity material-design


【解决方案1】:

mContext 可能不是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;
}

【讨论】:

  • 编辑了库的代码,现在它可以工作了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多