现在的位置: 首页 > 综合 > 正文

Android Training精要(一)ActionBar上级菜单导航图标

2014年08月29日 ⁄ 综合 ⁄ 共 1006字 ⁄ 字号 评论关闭

Navigation Up(ActionBar中的上级菜单导航图标)

在android 4.0中,我们需要自己维护activity之间的父子关系。

导航图标ID为android.R.id.home

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // This is called when the Home (Up) button is pressed
            // in the Action Bar.
            Intent parentActivityIntent = new Intent(this, MyParentActivity.class);
            parentActivityIntent.addFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(parentActivityIntent);
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

当然,android还给我们提供了utility方法实现这一功能,首先,我们要给activity添加如下属性:

<meta-data android:name="android.support.PARENT_ACTIVITY"
                       android:value=".ParentActivity" />

然后,在onOptionsItemSelected方法中,调用如下方法:

NavUtils.navigateUpFromSameTask(this);

Android4.1的Up实现

在android4.1及以后的版本中,android已经帮我们完成了大部分的功能,只要给activity添加如下属性android:parentActivityName,android会自动维护activity之间的父子关系,我们不需要为up实现任何代码。

<activity android:name=".ChildActivity"
                  android:label="@string/child_label"
                  android:parentActivityName=".ParentActivity">
</activity>

抱歉!评论已关闭.