简体   繁体   English

父活动的Android实例

[英]Android instance of parent activity

I have 2 activities, A & B for example. 我有2个活动,例如A&B。 I navigate to Activity B within Activity A using startActivity() 我使用startActivity()导航到活动A中的活动B

My question is when I'm on Activity B, how can I get access to activity A ? 我的问题是当我在活动B上时,我如何才能访问活动A?

Thanks, 谢谢,

To access functionality that is shared between Activities, it is a best practice to move that functionality to an Application class, or some other form of Singleton. 要访问活动之间共享的功能,最好将该功能移动到Application类或其他形式的Singleton。 The reason for that is the activity lifecycle does not allow you to be certain that the exited activity still exists while the focused activity is running. 原因是活动生命周期不允许您确定在焦点活动运行时退出的活动仍然存在。 So you need to use an object that is able to be persistent between activities, even of Activity.finish() is called on either activity. 因此,您需要使用一个能够在活动之间持久化的对象,甚至在任一活动上调用Activity.finish()。

Here is documentation on the Application class. 这是Application类的文档。 http://developer.android.com/reference/android/app/Application.html http://developer.android.com/reference/android/app/Application.html

You can access the application from within any activity by calling 您可以通过调用从任何活动中访问该应用程序

this.getApplication();

It really depends on what you want to do, and why you think you need that access. 这实际上取决于您想要做什么,以及您认为自己需要访问权限的原因。 One thing you can do is pass data into an activity using intent.putExtra and then startActivityForResult and listen for results in onActivityResult . 您可以做的一件事是使用intent.putExtra将数据传递到活动中,然后使用startActivityForResult并在onActivityResult侦听结果。 Can you give more information on what exactly you want to do? 你能提供更多关于你想做什么的信息吗?

To perform a method when an activity finishes, call the 'child' activity like this: 要在活动完成时执行方法,请像这样调用'child'活动:

Intent child = new Intent(this, ChildActivity.class);
startActivityForResult(child, CHILD_CODE);

where CHILD_CODE is a nonnegative integer field. 其中CHILD_CODE是非负整数字段。 Now, you have to set a result in the 'child' activity (the one you started with onActivityResult ). 现在,您必须在“子”活动(您使用onActivityResult开始的活动)中设置结果。

    Intent resultIntent = new Intent();
    setResult(Activity.RESULT_OK, resultIntent);
    finish();

now in your 'parent' activity, implement the onActivityResult method like this: 现在在“父”活动中,实现onActivityResult方法,如下所示:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case CHILD_CODE:
        if (resultCode == Activity.RESULT_OK) {
            yourMethod();
        }
    }
}

为什么不使用Actvity可以访问的单例类?

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

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