按下后不会调用onActivityResult

时间:2019-03-06 14:15:37

标签: android

我正在开发一个从活动变为子活动的应用程序,当按下后退按钮时,它将返回到具有两个数据的父活动,即网格中的行号和列号。这些值已存储在变量中,但是当按下后退按钮时,不会调用onActivityResult方法。

父级活动:onClick方法 `

view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity", "beginning");
                startActivityForResult(new Intent(getApplicationContext(), GridActivity.class), REQUEST_CODE);
            }
        });`

父级活动:onActivityResult方法

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("MainActivity", "receiving data");
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("MainActivity", "receiving data1");
        if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Log.d("MainActivity", "result ok");
            if(data != null) {
                if (data.getIntExtra(COL_VALUE_TOKEN, 999) != 999) {
                    rowValue.setText(data.getIntExtra(ROW_VALUE_TOKEN, 999));
                    colValue.setText(data.getIntExtra(COL_VALUE_TOKEN, 999));
                    Log.d("MainActivity", "data not 999");
                } else {
                    rowValue.setText("-");
                    colValue.setText("-");
                    Log.d("MainActivity", "data 999");
                }
            }
        }
    }

子活动:onClick方法

(findViewById(R.id.btn_ok)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

子活动:onBackPressed方法

@Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(COL_VALUE_TOKEN, currentCol);
        intent.putExtra(ROW_VALUE_TOKEN, currentRow);
        setResult(RESULT_OK, intent);
        Log.d("MainActivity", "sending data"+currentCol+currentRow);
        finish();
    }

清单文件:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".GridActivity"
            android:parentActivityName=".MainActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

1 个答案:

答案 0 :(得分:0)

您需要执行以下操作:

override fun onBackPressed() {
        setResult(Activity.RESULT_CANCELED)
        finish()
    }