在屏幕旋转时,不会调用onCreate()活动

时间:2016-06-30 14:56:08

标签: android android-fragments appcompatactivity

我有一个活动和附加的片段。这是我的活动代码:

public class GeneralSettingActivity extends BasePreferenceActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        //addPreferencesFromResource(R.xml.redesign_general_prefs);
        Log.e("Sushil", "...RedesignGeneralSettingsActivity onCreate()....");

        initGeneralSettingsFragment(savedInstanceState);

    }

    private void initGeneralSettingsFragment(Bundle bundle) {
        if (bundle == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragments_container, mGeneralSettingsFragment = new GeneralSettingsFragment(), ALARM_GENERAL_SETTINGS_FRAGMENT_TAG)
                    .commit();
        } else {
            mGeneralSettingsFragment = (GeneralSettingsFragment) getSupportFragmentManager().findFragmentByTag(ALARM_GENERAL_SETTINGS_FRAGMENT_TAG);
        }
    }
----
----

这是我的片段代码:

public class GeneralSettingsFragment extends PreferenceFragmentCompat {

    private GeneralSettingActivity mParentActivity;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mParentActivity = (GeneralSettingActivity)getActivity();

        (!mParentActivity.mPrefs.contains(SharedPreferencesWrapper.GeneralSettingKeys.CLOCK_24_HOURS))

------
------

当我旋转屏幕时,我的片段onCreate被调用,但我的活动onCreate不再被调用。对于活动,我没有在清单文件中进行任何设置来阻止活动被破坏。

有人可以帮助我找出为什么我的活动onCreate没有被调用。我的活动最终来自AppCompatActivity。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

尝试添加AndroidManifest.xml

<activity android:name=".GeneralSettingActivity "
          android:configChanges="orientation">

调用活动中的onConfigurationChanged来处理旋转事件

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

答案 1 :(得分:0)

在活动中添加android:screenOrientation =“ fullSensor”会触发onCreate需要调用。