从子activity调用 parent activity

4 Answers

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.

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");
}

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.

EDIT:

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.

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());
    }
  }
}

In First.class:

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

In Second.class:

Activity first = (First) getParent();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值