在的onActivityResult动作条的后退按钮被点击时不叫 [英] onActivityResult is not called when the back button in ActionBar is clicked

查看:182
本文介绍了在的onActivityResult动作条的后退按钮被点击时不叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的问题:


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

  1. Create a MainActivity. Add a button which will start another activity SecondActivity.

        Intent i = new Intent(getActivity(),SecondActivity.class);
        startActivityForResult(i,0);


  • 在SecondActivity,我捕捉到后退按钮单击事件,并添加一个按钮返回到第一个活动。

  • Inside the SecondActivity, I capture the back button click event and also add a button to return to the first Activity.

    当在操作栏中的后退按钮被点击:

    When back button in action bar is clicked:

    @覆盖

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

    在活动里面的按钮被点击:

    When the button inside activity is clicked:

    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中的后退按钮从来没有被调用。谁能告诉我为什么?谢谢

    The onActivityResult in MainActivity is called when I click the button inside the SecondActivity, but it's never been called if I click the back button in Actionbar of SecondActivity. Can anybody tell me why? Thanks

    推荐答案

    下面是code这是工作的:

    Here is the code which is working:

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

    我想结束()将关闭当前的活动,并返回true将该行动告知已被处理。 (默认回动作似乎是从完成()不同)。

    I guess the finish() will close the current Activity, and return true inform that action has been processed. (The default back action seems to be different from finish().)

    这篇关于在的onActivityResult动作条的后退按钮被点击时不叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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