I noticed this: I have a parent activity A which opens child activity B with startActivity(intent). In the activity B if I will finish() this activity in some way the parent activity will be loaded again from initial state, but if I will hit the back keyboard button I will be returned to activity A as in the state in which I left it.
Here is an example of how I am finishing activity B:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.icon:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Here is how I open activity B from activity A:
Intent intent = new Intent(thisActivity, toActivity);
startActivity(intent);
And here is the Manifest XML:
<activity
android:name="com.evapp.activities.A"
android:label="@string/A" >
</activity>
<activity
android:name="com.evapp.activities.B"
android:configChanges="orientation"
android:label="@string/B"
android:parentActivityName="com.evapp.activities.A"
android:screenOrientation="portrait" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.evapp.activities.A" />
</activity>
Can someone please explain me the deference between finish() and return?
Calling finish() and pressing the back button is not exactly the same when you are using fragments. If we check the source code of an Android Activity, we can see that it doesn't simply call finish() immediately, but calls it's FragmentManagers's popBackStackImmediate() method before that.
/**
* Called when the activity has detected the user's press of the back
* key. The default implementation simply finishes the current activity,
* but you can override this to do whatever you want.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
What popBackState() does is it removes the latest fragment from the back stack. Immediate simply means that it does it immediately instead of asynchronously. It returns false only when no fragment was removed - in that case finish() will be called.
I am not sure why your first activity seems to be reinitialized when calling finish(). In the case that you really get back to your first activity, it's onResume() method should get executed which might change it's appearance. To fully understand what's going on, we should see how you are creating your fragments and what happens in the onResume() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With