【发布时间】:2017-06-15 21:52:34
【问题描述】:
我只是想在按下“返回”按钮时将对象信息从 Activity2 交换回 Activity1。
一切正常,除了返回 Activity1 onActivityResult(..) 永远不会触发。因此我无法访问意图信息。有谁知道为什么?
我检查了这些答案,但它们不起作用:
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();
}
}
【问题讨论】:
-
onBackPressed()很可能为时已晚。当用户在你的 UI 中做一些积极的事情来说出他们想要什么(例如,单击列表项)时,调用setResult()。通常,您还会调用finish(),因为一旦用户决定了他们想要什么,就不再需要Activity2。 -
我还尝试在 Activity2 更新某些内容时设置结果(xxx)。仍然...看起来 Activity1 通常忽略回调。
标签: android onactivityresult onbackpressed