Saturday 28 September 2013

Android activities hierarchy

In this post I will mention couple of ways to make sure that parent / child relationship is maintained between activities. This is essential to make sure that the system knows which activity to start when Up is pressed on phone or action bar.

   
 This relationship have to be specified in AndroidManifest.xml file as shown below.

<activity
    ...
    android:parentActivityName="com.example.app.MainActivity" >
</activity>


In order to support API levels 4 - 16, <meta-data> element that specifies a value for "android.support.PARENT_ACTIVITY" can be declared. For example above activity information can be changed as shown below.

<activity
    ...
    android:parentActivityName="com.example.app.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.calc18.MainActivity" />
</activity>



If you are using Eclipse IDE it will be done automatically when activity is created, by specifying the Hierarchical Parent as shown below.



In case of ActionBar I have seen that Up button starts the parent activity instead of finishing the child activity. This results in calling of onCreate( ) method which destroys the previous state of activity. I have seen this behavior occurring with Android 4.3 API Level 18. As a workaround I used following procedure.

In order for parent child relation to work in case of ActionBar make sure to replace 
NavUtils.navigateUpFromSameTask(this); with finish( ) statement in onOptionsItemSelected( ) in child activity. This function should look like following.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case android.R.id.home:
     finish();
     return true;
  }
 return super.onOptionsItemSelected(item);
}





No comments:

Post a Comment