访问父活动的实例? [英] Accessing instance of the parent activity?

查看:89
本文介绍了访问父活动的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一类first.java(活动类),我开始另一项活动在这个类(second.java - 活动类)。如何从second.java访问first.java的实例?有人可以给我一个很好的解释这个。一个例子是伟大的......

Suppose i have a class first.java(activity class) and i start another activity in this class (second.java - activity class). How can i access the instance of first.java from second.java ? Can someone give me a good explanation on this.. An example would be great...

推荐答案

如果你需要你的第二个活动的一些数据返回给你的第一个活动,我建议你使用startActivityForResult()来开始你的第二个活动。然后,在onResult()中的第一个活动,你可以做的工作需要。

If you need your second activity to return some data to your first activity I recommend you use startActivityForResult() to start your second activity. Then in onResult() in your first activity you can do the work needed.

在First.java你开始Second.java:

In First.java where you start Second.java:

Intent intent = new Intent(this, Second.class);
int requestCode = 1; // Or some number you choose
startActivityForResult(intent, requestCode);

结果的方法:

The result method:

protected void onActivityResult (int requestCode, int resultCode, Intent data) {
  // Collect data from the intent and use it
  String value = data.getString("someValue");
}

在Second.java:

In Second.java:

Intent intent = new Intent();
intent.putExtra("someValue", "data");
setResult(RESULT_OK, intent);
finish();

如果您不希望等待第二个活动结束你在第一次活动有一定的工作之前,你可以改为发送广播其中第一个活动作出反应。

If you do not wish to wait for the Second activity to end before you do some work in the First activity, you could instead send a broadcast which the First activity reacts to.

编辑:

如果您需要访问你的第一个活动有一定的值,而不进行的静态引用它,你可以考虑把你的活动中的ActivityGroup。

If you need access to some values in your First activity without making a static reference to it, you could consider putting your activities in an ActivityGroup.

所以,的ActivityGroup开始的第一个活动。然后第一个活动使用的ActivityGroup启动第二个活动。然后,你将不得不通过在第二个活动调用的getParent()获得的第一个活动。

So, the ActivityGroup starts the First activity. And then the First activity uses the ActivityGroup to start the Second activity. Then you will have access to the First activity through a call to getParent() in the Second activity.

class MyActivityGroup extends ActivityGroup {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startChildActivity("first", new Intent(this, First.class));
  }
  public void startChildActivity(Intent intent) {
    Window window = getLocalActivityManager().startActivity(id, intent);
      if (window != null) {
        setContentView(window.getDecorView());
    }
  }
}

在First.class:

In First.class:

Intent = new Intent(this, Second.class);
((MyActivityGroup) getParent()).startChildActivity("second", intent);

在Second.class:

In Second.class:

Activity first = (First) getParent();

这篇关于访问父活动的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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