4

这是我的问题:

  1. 创建一个主活动。添加一个按钮,它将启动另一个活动 SecondActivity。

            Intent i = new Intent(getActivity(),SecondActivity.class);
            startActivityForResult(i,0);
    
  2. 在 SecondActivity 中,我捕获了后退按钮单击事件,并添加了一个返回到第一个 Activity 的按钮。

    单击操作栏中的后退按钮时:

@覆盖

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            // back button
            Intent resultIntent = new Intent();
            // TODO Add extras or a data URI to this intent as appropriate.
            setResult(Activity.RESULT_OK, resultIntent);
            //finish();
            return false;

    }
    return super.onOptionsItemSelected(item);
}

当点击活动内的按钮时:

Button btn = (Button)this.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent resultIntent = new Intent();
        // TODO Add extras or a data URI to this intent as appropriate.
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    }
});

当我单击 SecondActivity 内的按钮时,会调用 MainActivity 中的 onActivityResult,但如果单击 SecondActivity 的 Actionbar 中的后退按钮,则不会调用它。谁能告诉我为什么?谢谢

4

3 回答 3

4

这是正在运行的代码:

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            // back button
            Intent resultIntent = new Intent();
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
            return true;

    }
    return super.onOptionsItemSelected(item);
}

我猜finish() 会关闭当前的Activity,并返回true 通知动作已经被处理。(默认的后退操作似乎与 finish() 不同。)

于 2013-11-23T10:46:23.183 回答
1

试试这个:-

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
    case android.R.id.home:
        Intent resultIntent = new Intent();
        setResult(Activity.RESULT_OK, resultIntent);
        onBackPressed();
        return true;
}
return super.onOptionsItemSelected(item);
}
于 2013-11-23T10:53:25.337 回答
1

好的答案是同一问题中的 Gopal Rao 代码。它对我有用。这是他的解决方案的副本:

    public boolean onOptionsItemSelected(MenuItem item) {
       if (item.getItemId() == android.R.id.home) {
          Intent result = new Intent((String) null);
          result.putExtra("SOME_CONSTANT_NAME", true);
          setResult(RESULT_OK, result);
          finish();
          return true;
       } 
       else {
          return super.onOptionsItemSelected(item);
       }
    }
于 2014-04-11T08:42:52.853 回答