在Manifest中声明Activity的父Activity

声明了Activity的父Activity之后,点击该Activity的up按钮后,可以直接跳到父Activity


如果应用支持的版本是Android 4.1以上,那么直接在Activity标签中声明android:parentActivityName 属性即可

如果应用支持4.1以下的版本,那么需要在Activity标签中增加


            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />

例子如下:

 ... >
    ...
    
    
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    
    
    
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        
        
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    

另外,在点击Up按钮之后,在onOptionsItemSelected方法中,应该进行判断:是否要新建Task Stack,

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        Intent upIntent = NavUtils.getParentActivityIntent(this);
        if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
            // This activity is NOT part of this app's task, so create a new task
            // when navigating up, with a synthesized back stack.
            TaskStackBuilder.create(this)
                    // Add all of this activity's parents to the back stack
                    .addNextIntentWithParentStack(upIntent)
                    // Navigate up to the closest parent
                    .startActivities();
        } else {
            // This activity is part of this app's task, so simply
            // navigate up to the logical parent activity.
            NavUtils.navigateUpTo(this, upIntent);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}

你可能感兴趣的:(在Manifest中声明Activity的父Activity)