purserj
purserj

Reputation: 145

Launching an Intent outside an activity

I have an asynch task with my app which goes to a website, grabs the results from the API and appends a number of clickable textviews to an existing LinearLayout.

However I want to be able to launch a new activity when the textview is clicked. This isn't possible with the asynch class defined in a seperate file, would it be easier to define it as an inline class within the activity?

Upvotes: 1

Views: 805

Answers (3)

rotterick
rotterick

Reputation: 31

Do not use a context as an Activity! You will probably receive a cast error anyway. Instead, you can pass the activity as a function parameter, like this:

 public void function(Activity act)
 {
   Intent intent = new Intent(act, newActivity.class);
   act.startActivity(intent);
 }

Or overload the constructor to accept the activity as a parameter. But I strongly suggest you to check you code. If you are calling an activity, you, probably, should be within another one, don't you agree? But, I Know that sometimes we have to make a few concessions, in order to make things work properly. So, use it wisely.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

One approach is to inflate your TextViews from an XML file that declares an onClick attribute, naming a method defined in your Activity.

Upvotes: 1

sgarman
sgarman

Reputation: 6182

You can always pass Context to your async class.

A better approach would be to have callbacks (listeners) in the calling class for the async to call back to.

Upvotes: 3

Related Questions