您的位置:首页 > 移动开发 > Android开发

android提供的向上导航栏

2016-06-27 19:48 423 查看
 使用Android自带的返回操作

在AndroidManifest.xml中<activity>标签添加属性android:parentActivityName=".MainActivity"。或者添加<meta-data>标签,<meta-data>添加android:name属性,对应的值是android.support.PARENT_ACTIVITY,添加android:value属性,对应的值是父Activity的名称。如下所示:

<meta-data

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


<activity>标签添加主题:android:theme="@android:style/Theme.Holo.Light.DarkActionBar",添加之后导航栏返回图标是一个左箭头的小图标。


在SecondActivity中实现onoOptionsItemSelected(MenuItem item)方法,添加如下代码:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
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);
}


NavUtils位于android.support.v4.app.NavUtils包中。常用方法介绍,用法在onOptionsItemSelected方法中进行了说明。

public static
Intent getParentActivityIntent
(Activity sourceActivity)

参数:sourceActivity要返回到上一个页面的当前页面。

返回:返回当前页面的上一级Activity或者null。

public static boolean shouldUpRecreateTask(Activity
sourceActivity,Intent targetIntent)

参数:sourceActivity用户尝试导航到上一个页面的当前Activity页面

          targetIntent 代表导航的目标Intent。

返回值:返回true导航到上一个页面应该重新创建一个新的任务栈,返回false同样的任务栈应该被使用作为目标Intent。

public static void navigateUpTo(Activity
sourceActivity,Intent upIntent)

参数:sourceActivity 当前Activity,用户正在尝试导航到上一个页面。

upIntent 一个Intent代表要导航到上一级页面的Intent。

参考:http://blog.csdn.net/aikongmeng/article/details/37934741
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 自带导航栏