确保您在“活动”中启用了“操作栏”主页按钮:
Android, API 5+:
@Override
public void onBackPressed() {
...
super.onBackPressed();
}
ActionBarSherlock and App-Compat, API 7+:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Android, API 11+:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
...
getActionBar().setDisplayHomeAsUpEnabled(true);
}
扩展的示例:MainActivity
ActionBarActivity
public class MainActivity extends ActionBarActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// API 5+ solution
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
这样,您想要的所有活动都可以进行反冲。
Android, API 16+:
http://developer.android.com/training/implementing-navigation/ancestral.html
AndroidManifest.xml
:
<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
android:name="com.example.myfirstapp.MainActivity" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
扩展的示例:MainActivity
ActionBarActivity
public class MainActivity extends ActionBarActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Back button
getSupportActionBar().setDisplayHomeAsUpEnabled(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);
}
}