Invoking intent from a fragment

a 夏天 提交于 2020-04-30 07:37:14

问题


I have a fragment

public class TwitterFragment extends Fragment implements OnClickListener {}

From this fragment I am invoking an intent as:

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

where,

public class WebViewActivity extends Activity {

But Invoking intent is giving error:

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)

This code was working when TwitterFragment class extends Activity instead of fragment.


回答1:


Fragment is not a Context. Try this:

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



回答2:


Intent demands a Context as its first parameter. Do this:

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

And to actually start your Activity, do this:

getActivity().startActivity(intent);

Fragment doesn't extend Context, so it borrows it from its housing Activity. That is why you can't get your Intent working the first time you try it.




回答3:


Get the activity for the context parameter

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



回答4:


Use getActivity() instead of this. Intent intent = new Intent(getActivity(), WebViewActivity.class);



来源:https://stackoverflow.com/questions/31419891/invoking-intent-from-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!