Android 在不处理向上按钮事件的情况下导航回 ActionBar 中的父活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20303657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:36:56  来源:igfitidea点击:

Navigating back to parent activity in ActionBar without handling Up button event

androidandroid-actionbar

提问by Tarik

I have two activities that I want this navigation to happen, they are VendorsActivity and QuestionsActivity. The following how my AndroidManifest.xml looks like:

我有两个活动希望发生此导航,它们是 VendorsActivity 和 QuestionsActivity。以下是我的 AndroidManifest.xml 的样子:

(I am not using the full name of my activities like com.hello.world.MyActivityas I am defined packageattribute in manifestnode.)

(我没有使用我的活动的全名,就像com.hello.world.MyActivitypackagemanifest节点中定义的属性一样。)

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".VendorsActivity"
        android:label="@string/vendors_activity_title" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TestsActivity"
        android:label="@string/tests_activity_title"
        android:parentActivityName=".VendorsActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".VendorsActivity" />
    </activity>
    <activity
        android:name=".QuestionsActivity"
        android:label="@string/questions_activity_title" >
    </activity>
</application>

And in TestsActivity, I am calling getActionBar().setDisplayHomeAsUpEnabled(true);method from within onCreatemethod.

在 中TestsActivity,我getActionBar().setDisplayHomeAsUpEnabled(true);onCreate方法内部调用方法。

The problem is, it won't work unless I implement the following method in .TestsActivityclass:

问题是,除非我在.TestsActivity课堂上实现以下方法,否则它将无法工作:

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

But Android Developer Guide says that I don't have to handle the Up button's event as mentioned at the very bottom of hit page: https://developer.android.com/training/basics/actionbar/adding-buttons.html

但是Android开发人员指南说我不必处理点击页面最底部提到的向上按钮事件:https: //developer.android.com/training/basics/actionbar/adding-buttons.html

Because the system now knows MainActivity is the parent activity for DisplayMessageActivity, when the user presses the Up button, the system navigates to the parent activity as appropriate—you do not need to handle the Up button's event.

因为系统现在知道 MainActivity 是 DisplayMessageActivity 的父活动,所以当用户按下向上按钮时,系统会根据需要导航到父活动——您不需要处理向上按钮的事件。

Edit and Answer:

编辑和回答:

As Android Developer Guide says:

正如 Android 开发者指南所说:

Beginning in Android 4.1 (API level 16), you can declare the logical parent of each activity by specifying the android:parentActivityName attribute in the element.

If your app supports Android 4.0 and lower, include the Support Library with your app and add a element inside the . Then specify the parent activity as the value for android.support.PARENT_ACTIVITY, matching the android:parentActivityName attribute.

从 Android 4.1(API 级别 16)开始,您可以通过在元素中指定 android:parentActivityName 属性来声明每个 Activity 的逻辑父级。

如果您的应用支持 Android 4.0 及更低版本,请在您的应用中包含支持库并在 . 然后将父活动指定为 android.support.PARENT_ACTIVITY 的值,与 android:parentActivityName 属性匹配。

So I think my problem was because of two reasons:

所以我认为我的问题是由于两个原因:

  1. Running the app on a proper emulator. I was targeting a higher version but the emulator was running on API 14 (Android 4.0) so it didn't know how to handle android:parentActivityNameattribute.

  2. Targeting the right API level in Project Build Target properties as shown below:

  1. 在适当的模拟器上运行应用程序。我的目标是更高版本,但模拟器运行在 API 14 (Android 4.0) 上,所以它不知道如何处理android:parentActivityName属性。

  2. 在 Project Build Target 属性中定位正确的 API 级别,如下所示:

enter image description here

在此处输入图片说明

采纳答案by Rahul Gupta

android:parentActivityName attribute supported only after API level.

android:parentActivityName 属性仅在 API 级别后支持。

One alternative is using support-library:v7combined with NavUtils.

一种替代方法是将support-library:v7NavUtils结合使用。

There is a great training material about this topic (include compatibility issue). please check - http://developer.android.com/training/implementing-navigation/ancestral.html

有关于这个主题的很好的培训材料(包括兼容性问题)。请检查 - http://developer.android.com/training/implementing-navigation/ancestral.html

That being said, i am posting my code below because it is working :-

话虽如此,我在下面发布我的代码,因为它正在工作:-

MainActivity.Java

主Activity.Java

package com.example.activitydatasend;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button click = (Button) findViewById(R.id.click);

        click.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this,Second.class);
                intent.putExtra("first", "first");
                intent.putExtra("second", "second");
                startActivity(intent);

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

SecondActivity.java

第二个Activity.java

package com.example.activitydatasend;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class Second extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        Bundle bundle = getIntent().getExtras();
        String a = bundle.getString("first");
        String b = bundle.getString("second");
        System.out.println(a+b);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

AndroidManifext.xml

AndroidManifext.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.activitydatasend"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.activitydatasend.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.activitydatasend.Second"
            android:label="@string/app_name"
            android:parentActivityName="com.example.activitydatasend.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

活动_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/click"
        android:text="Click" />

</RelativeLayout>

second.xml

第二个.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

回答by Kalel Wade

If you receive an error similar to

如果您收到类似于以下内容的错误

E/NavUtils﹕ getParentActivityIntent: bad parentActivityName

or

或者

does not have a parent activity name specified. (Did you forget to add the android.support.PARENT_ACTIVITY <meta-data>  element in your manifest?)

You will probably need to change android:value to the full path. So instead of

您可能需要将 android:value 更改为完整路径。所以代替

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

do

 <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.package.SecondActivity" />

回答by fchristysen

you can add metadata in manifest to support pre JellyBean OS.

您可以在清单中添加元数据以支持 JellyBean 操作系统之前的版本。

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

回答by just me

What API version are you using? In my experience, for older versions it isnecessary to handle the up button event yourself, whereas with later versions it's done for you.

您使用的是什么 API 版本?根据我的经验,旧版本的它需要自己处理向上按钮事件,而更高版本的它为你做。

I haven't looked into which exact version changes this, but I know that API 13 doesn'thandle it for you, while API 16 does.

我还没有研究哪个确切的版本会改变这个,但我知道 API 13不会为你处理它,而 API 16