【问题标题】:Invoking intent from a fragment从片段调用意图
【发布时间】:2015-07-15 01:14:31
【问题描述】:

我有一个片段

public class TwitterFragment extends Fragment implements OnClickListener {}

从这个片段中,我调用了一个意图:

Intent intent = new Intent(this, WebViewActivity.class);

在哪里,

public class WebViewActivity extends Activity {

但是调用意图给出错误:

Error:(214, 33) error: no suitable constructor found for Intent(TwitterFragment,Class<WebViewActivity>)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; TwitterFragment cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; TwitterFragment cannot be converted to Context)

当 TwitterFragment 类扩展 Activity 而不是片段时,此代码有效。

【问题讨论】:

    标签: java android android-fragments android-intent


    【解决方案1】:

    Fragment 不是Context。试试这个:

    Intent intent = new Intent(getActivity(), WebViewActivity.class);
    

    【讨论】:

      【解决方案2】:

      Intent 需要 Context 作为其第一个参数。这样做:

      Intent intent = new Intent(getActivity(), YourTargetClass.class);
      

      要真正开始您的Activity,请执行以下操作:

      getActivity().startActivity(intent);
      

      Fragment 没有扩展Context,所以它从它的外壳Activity 中借用它。这就是为什么您第一次尝试时无法让您的Intent 工作的原因。

      【讨论】:

      • 我不敢相信这个 xD
      【解决方案3】:

      获取上下文参数的活动

      Intent intent = new Intent(getActivity(), WebViewActivity.class);
      

      【讨论】:

        【解决方案4】:

        使用 getActivity() 代替这个。 Intent 意图 = new Intent(getActivity(), WebViewActivity.class);

        【讨论】:

          猜你喜欢
          • 2014-11-14
          • 1970-01-01
          • 1970-01-01
          • 2019-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-07
          • 1970-01-01
          相关资源
          最近更新 更多