gpt4 book ai didi

android - onActivityResult() 未在 onBackPressed() 上触发

转载 作者:行者123 更新时间:2023-11-29 14:45:07 28 4
gpt4 key购买 nike

我只是想在按下“后退”按钮时将对象信息从 Activity2 交换回 Activity1。一切正常,除了 Activity1 中的 onActivityResult(..) 永远不会被触发。 因此我无法访问 Intent 信息。谁知道为什么?

我检查了这些答案,但它们不起作用:

setResult does not work when BACK button pressed

How to pass data from 2nd activity to 1st activity when pressed back? - android

How to pass the values from one activity to previous activity

Send data to a parent activity onBackPressed

我的代码(如果你需要更多,告诉我):

AndroidManifest.xml:

        <activity
android:name="com.example.Activity1"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name="com.example.Activity2"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait">
</activity>

Activity1.java:

public class MainActivity extends AppCompatActivity {

// other stuff...

private void showActivity2(Test test) {
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("test", test.getSerializableObject());
startActivityForResult(intent, Activity.RESULT_OK);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Test test = data.getExtras().getParcelable("test");
// Do something...
}
}

Activity2.java:

public class Activity2 extends AppCompatActivity {

// other stuff....

@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("test", test.getSerializableObject());
setResult(Activity.RESULT_CANCELED, intent);
super.onBackPressed();
}
}

最佳答案

根据 startActivityForResult 的 android 文档

Same as calling startActivityForResult(Intent, int, Bundle) with no options.

intent Intent: The intent to start.

requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.

现在您所做的是:startActivityForResult(intent, Activity.RESULT_OK);

Activity.RESULT_OK实际值为 -1,这就是它不返回结果的原因。当您开始一个结果 Activity 时,您需要有一个有效的请求代码,然后在您的 onActivityResult 中过滤请求代码。

关于android - onActivityResult() 未在 onBackPressed() 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941009/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com