1

我只想创建一个简单的返回(主页)按钮,但出现以下错误

e(12674): FATAL EXCEPTION: main
06-11 15:38:59.910: E/AndroidRuntime(12674): java.lang.IllegalArgumentException: Activity DevicesActivity does not have a parent activity name specified. (Did you forget to add the android.support.PARENT_ACTIVITY <meta-data>  element in your manifest?)
06-11 15:38:59.910: E/AndroidRuntime(12674):    at android.support.v4.app.NavUtils.navigateUpFromSameTask(NavUtils.java:74)
06-11 15:38:59.910: E/AndroidRuntime(12674):    at com.example.wip.DevicesActivity.onOptionsItemSelected(DevicesActivity.java:252)
06-11 15:38:59.910: E/AndroidRuntime(12674):    at com.actionbarsherlock.app.SherlockExpandableListActivity.onMenuItemSelected(SherlockExpandableListActivity.java:197)
06-11 15:38:59.910: E/AndroidRuntime(12674):    at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)

我的代码:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

显现

   <activity
            android:name="com.project.project1.MainActivity"
            android:label="Project1" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity
            android:name="com.project.project1.SecondActivity"
            android:label="@string/title_activity_second"
            android:parentActivityName="com.project.wip.MainActivity" >
        </activity>

我也可以做这样的事情吗?该代码有效。下面的代码有什么不好的吗?

    case android.R.id.home:
    Intent intent = new Intent(secondActivity.this,
                        MainActivity.class);
   startActivity(intent);
    return true;
4

1 回答 1

1

您的代码的问题在于您的清单中没有以下代码:

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

您使用的设备可能不是 ICS,这就是它无法正常工作的原因。

您在底部的代码没有任何问题,但我会将其放入如下菜单中:

@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);
            ...
    case android.R.id.home:
    Intent intent = new Intent(secondActivity.this,
                        MainActivity.class);
      startActivity(intent);
      ....

    return true;
}

这将为您添加按钮以转到其他区域以及家庭奠定基础。

于 2013-06-11T16:47:28.453 回答