我只想创建一个简单的返回(主页)按钮,但我收到以下错误
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;
答案 0 :(得分: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;
}
这将为您添加按钮以转到其他区域以及家中奠定基础。