如何回到上一个 activity

How to go back to previous activity

我对 android 上的活动生命周期有疑问。我正在尝试 return 从我的第二个 activity 回到我的第一个。实际上我的代码是这样做的,而不是它应该做的方式。我在左上角有“后退按钮”,当我点击它时 - 它会通过我的 onDestroy()onCreate() 方法主要活动。但是如果我在 phone 上使用后退按钮 - 一切正常(它只是通过 onResume() 方法)有人可以解释我 - 我的代码哪里错了吗?

在MainActivity.java中:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.settings_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

在我的 SettingsActivity.java:

package com.example.garagedoor;

import android.os.Bundle;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;

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);
        }
    }
}

在AndroidManifest.xml中:

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".SettingsActivity"
        android:label="@string/title_activity_settings"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>

您的问题可能与任务堆栈有关。我不确定操作栏按钮的作用,但我认为您应该使用

@Override public void onBackPressed()

SettingsActivity 中或使用 Intent 标志 启动 SettingsActivity,如下所示:

https://developer.android.com/guide/components/activities/tasks-and-back-stack

希望对您有所帮助。

您需要添加

android:launchMode="singleTop"

MainActivity 的清单条目。请参阅以下问题:

ActionBar up navigation recreates parent activity instead of onResume

How can I return to a parent activity correctly?