如何通过操作栏返回上一个活动?

时间:2014-05-17 13:30:15

标签: android android-layout android-fragments android-actionbar

我有一个带动作栏的活动,我想回到上一个,我怎么能用动作栏呢?

1 个答案:

答案 0 :(得分:3)

添加getActionBar().setDisplayHomeAsUpEnabled(true);

并覆盖onOptionsItemSelected(),如下所示:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

还在清单文件中指定父活动:

例如:

<application ... >
...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>