android - 使用onactivityresult android

标签 android

我想在其他 Activity 中调用 mainactivity 中的方法。为此,我进行了很多研究,发现使用 OnActivityResult 是最好的选择。谁能在示例的帮助下解释如何使用此方法?我经历过类似的问题,但发现它们令人困惑。 谢谢!

编辑:我的应用中有一个自定义对话框 Activity 。它询问用户是否要开始新游戏,它有两个按钮是和否。我想实现上述方法只是为了获得按下的按钮。

最佳答案

定义常量

public static final int REQUEST_CODE = 1;

使用 Intent 调用您的自定义对话框 Activity

Intent intent = new Intent(Activity.this,
                    CustomDialogActivity.class);
            startActivityForResult(intent , REQUEST_CODE);

现在使用 onActivityResult 检索结果

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

            if (requestCode == REQUEST_CODE  && resultCode  == RESULT_OK) {

                String requiredValue = data.getStringExtra("key");
            }
        } catch (Exception ex) {
            Toast.makeText(Activity.this, ex.toString(),
                    Toast.LENGTH_SHORT).show();
        }

    }

在自定义对话框 Activity 中使用此代码设置结果

Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();

关于android - 使用onactivityresult android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20114485/

相关文章:

android - 安装facebook app时无法实现facebook登录

android - android的READ_LOGS和READ_CALL_LOG权限的区别

java - 图标未显示在 ActionBar 中

android - react native (Android): Request failed with status code 403 - bscscan api testnet

java - List<double[]> 的最小最大值

Android XML 属性引用了另一个相同类型的 xml 属性

android - 将 Repo 与 Msysgit 结合使用

javascript - 使用 Web Bluetooth API 时找不到移动设备

android - java.lang.NoClassDefFoundError : Failed resolution of: Landroid/support/v4/animation/AnimatorCompatHelper

android - Fleetboard 上的 TLS 1.2