Calling startActivity() from outside of an Activit

2019-01-03 04:29发布

I have implemented a ListView in my Android application. I bind to this ListView using a custom subclass of the ArrayAdapter class. Inside the overridden ArrayAdapter.getView(...) method, I assign an OnClickListener. In the onClick method of the OnClickListener, I want to launch a new activity. I get the exception:

Calling startActivity() from outside of an Activity  context requires the  
FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

How can I get the Context that the ListView(the current Activity) is working under?

21条回答
Root(大扎)
2楼-- · 2019-01-03 04:35

I also had the same problem. Check all the context that you have passed. For 'links' it needs Activity Context not Application context.

This are the place where you should check :

1.) If you used LayoutInflater then check what context you have passed.

2.) If you are using any Adapter check what context you have passed.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-03 04:36

In addition: if you show links in listview in fragment, do not create it like this

    adapter = new ListAdapter(getActivity().getApplicationContext(),mStrings);

instead call

    adapter = new ListAdapter(getActivity(),mStrings);

adapter works fine in both cases, but links work only in last one.

查看更多
Fickle 薄情
4楼-- · 2019-01-03 04:37

Either

  • cache the Context object via constructor in your adapter, or
  • get it from your view.

Or as a last resort,

  • add - FLAG_ACTIVITY_NEW_TASK flag to your intent:

_

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.

查看更多
Bombasti
5楼-- · 2019-01-03 04:38

See, if you are creating an intent within a listiner in some method

override onClick (View v).

then call the context through this view as well:

v.getContext ()

There will not even need SetFlags ...

查看更多
ら.Afraid
6楼-- · 2019-01-03 04:40

Faced the same issue then implemented
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
and got solved the problem.

There may be an another reason which is related to list view adapter.
you can see This blog, described it very well.

查看更多
成全新的幸福
7楼-- · 2019-01-03 04:41

You can achieve it with addFlags instead of setFlags

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

According to the documentation it does:

Add additional flags to the intent (or with existing flags value).


EDIT

Be aware if you are using flags that you change the history stack as Alex Volovoy's answer says:

...avoid setting flags as it will interfere with normal flow of event and history stack.

查看更多
登录 后发表回答