在我的MainActivity
中,我定义了:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
switch (item.getItemId()) {
case R.id.menu_settings:
Toast.makeText(getApplicationContext(), "Settings menu clicked", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
case R.id.menu_location:
startLocationUpdates();
setupViewPager();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Settings Activity
是Android Studio创建的默认New->Activity->Settings
,如下所示:
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
现在,问题在于后退按钮实际上没有执行任何操作,即单击SettingsActivity上的后退按钮并不能将我带到MainActivity。
我该怎么办?
答案 0 :(得分:1)
尝试在AndroidManifest.xml中设置父级活动:
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
答案 1 :(得分:0)
尝试在Settings Activity
上实施
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() ==android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}