我只是想按下「後退」按鈕,將Activity2中的對象信息交換回Activity1。 一切工作正常,除了返回Activity1 onActivityResult(..)
永遠不會觸發。因此我無法訪問意向信息。有人知道爲什麼onActivityResult()onBackPressed()上沒有觸發
我檢查了這些問題的答案,但他們不工作:
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()'最可能爲時已晚。調用'setResult()'當用戶在UI中做出正面的事情來說出他們想要的是什麼(例如,單擊列表項)。通常,你也可以調用'finish()',因爲一旦用戶決定他們想要什麼,'Activity2'就不再需要了。 – CommonsWare
我也嘗試setResult(xxx),而Activity2正在更新的東西。仍然...看起來像Activity1通常忽略回調。 – Javatar