安卓:从另一个活动的活动获得方法 [英] Android: Access method in an activity from another activity

查看:274
本文介绍了安卓:从另一个活动的活动获得方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的发射活动启动另一个活动的启动设置为单一实例。在这第二个活动,我有一个公共的方法。然后,我开始了第三次活动,该活动需要访问公有方法在第二活动。我不想使用 startActivity 并把它传递群众演员,因为我承担了的onCreate 将被调用(还是我错了吗?),我需要避免重新初始化自己的第二个活动。

My launch activity starts up another activity whose launch is set to single instance. In this 2nd activity, I have a public method. I then start up a 3rd activity and that activity needs to access the public method in the 2nd activity. I don't want to use startActivity and pass it extras because I assume the onCreate will get called (or am I wrong?) and I need to avoid the 2nd activity from reinitializing itself.

在一个活动的启动是通过 startActivit Y,是否有可能获得基础类实例本身,只是调用的方法?

When an activity is started using startActivity, is it possible to gain access to the underlying class instance itself and simply call the method?

推荐答案

其实,我想出了一个简单的解决方案。作为事实上,你可以访问基础类的活动。首先,创建用于举行公开静态引用活动2类。当活动2创建在其onCreate方法你这一静态参考储存。活动2实现了与要提供给任何其他活动或对象的方法的接口。静态参考你持有会是这个接口的数据类型。在另一项活动希望本次活动调用一个方法,它只是访问公共静态参考,并调用该方法。这不是黑客,而是内在的Java如何操作,是完全合法的。

I actually came up with a simple solution. As a matter of fact you can access the underlying class of an activity. First, you create a class that is used to hold a public static reference to activity 2. When activity 2 is created, in its onCreate method you store "this" in the static reference. Activity 2 implements an interface with the methods that you want available to any other activity or object. The static reference you hold would be of a data type of this interface. When another activity wants to call a method in this activity, it simply accesses the public static reference and calls the method. This is no hack but is intrinsic to how Java operates and is totally legitimate.

这篇关于安卓:从另一个活动的活动获得方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆