我有一个具有" up"的SettingsActivity。顶部栏上的按钮。我的AettingsActivity也有标题,加载适当的设置片段。默认情况下,当我按顶栏时#34;向上"按钮,它关闭可见片段并返回标题,如果在标题视图上按下则关闭活动。但是,我的手机"返回"按钮工作不同 - 它只是关闭活动。我怎么做" up"箭头和后退按钮以同样的方式保持我的应用程序一致吗?我应该将onBackPressed添加到我的活动中吗?如果是,我应该把它放在那里?
我的设置活动:
public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| NewsPreferenceFragment.class.getName().equals(fragmentName)
|| OtherPreferenceFragment.class.getName().equals(fragmentName);
}
public static class NewsPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_news);
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public static class OtherPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_other);
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
这是在创建新的SettingsActivity时从Android Studio生成的默认代码,只是对我的应用进行了一些更改
答案 0 :(得分:1)
您只需要覆盖onBackPressed()
方法:
@Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
}