Simple use of up navigation
Up navigation help us use and organize our application hierarchy, Android offers built in features to implement this behavior easily. Here I present a simple use and an problem that I face while using it.
It is easy to use, just need this in your manifest:
<activity
android:name=".ui.activities.DetailActivity"
android:parentActivityName=".ui.activities.MainActivity" > //<---Only add this
<meta-data // This if you need to target Android versions lower than 16
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.activities.MainActivity" />
</activity>
Add android:parentActivityName="parentActivityName"
to the child activity in your manifest and you are up to use it.
It will add the back arrow to your child activity and when clicked it will go to the parent activity.
You don't need to write this anymore.
getActionBar().setDisplayHomeAsUpEnabled(true);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
// Code to go to the parent activity
return true;
}
return super.onOptionsItemSelected(item);
}
You will get the same functionality for free.
But one important think that I missed the first time I tried it, any time that you go to the parent activity using the up navigation (back arrow), the parent activity will be recreated, i.e. if it is a list you will go to the top element, if the parent activity has complex UI and images all of it will have to be recreated, worse, if the parent activity got some data from the Internet that was not cached, the whole download process will be done again. It is easy to fix this.
It is explained here Providing Up Navigation:
Just add launchMode="singleTop
to the parent activity.
<activity
android:name=".ui.activities.MainActivity"
android:launchMode="singleTop">
</activity>
This is a small article about a simple problem in a big feature. Up navigation and launch modes are a big topic, so be careful when you use them and read the documentation understand better what happens behind the scenes