简体   繁体   English

在活动之外启动意图

[英]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. 我的应用程序有一个asynch任务进入一个网站,从API中获取结果并将一些可点击的文本视图附加到现有的LinearLayout。

However I want to be able to launch a new activity when the textview is clicked. 但是,我希望能够在单击textview时启动新活动。 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? 对于在单独文件中定义的asynch类,这是不可能的,是否更容易将其定义为活动中的内联类?

You can always pass Context to your async class. 您始终可以将Context传递给异步类。

A better approach would be to have callbacks (listeners) in the calling class for the async to call back to. 更好的方法是在调用类中使用回调(侦听器)以便异步回调。

一种方法是从声明onClick属性的XML文件中扩展TextView,命名在Activity中定义的方法。

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. 所以,明智地使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM