My app in Android Studio using Kotlin restarts upon rotation (using seperate landscape and portait XML files)

30 Views Asked by At

So I'm making an application in Android Studio using Kotlin and have 2 xml files, one for portait mode and the other for landscape mode. Switching between them was fine but I noticed that the app "restarts" upon rotating, more specifically the data is reset. So if I interacted with the app and got new numbers, the numbers are reset upon rotating. Here's my AndroidManifest.xml file if it'll be of any help

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Weather">
    <activity

        android:name=".MainActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:exported="true">
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I saw some solutions like how in the AndroidManifest.xml file I can have something along the lines of android:configChanges="keyboardHidden|orientation|screenSize" but that only let's me keep my data after rotating but doesn't use the landscape xml file I have.

So what I'm trying to do is be able to switch from landscape to portrait mode and vice versa without resetting my data. So far, I either use only one of the XML files and not reset my data or use both XML files accordingly but my data resets. How do I make it so that I can use either XML file when rotating my phone without resetting the data?

1

There are 1 best solutions below

2
Nirali Pandya On

Your approach will keep the current layout as it is, including the one you had in portrait mode.

Try to set ,layout again when configuration change

 @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.activity_main);        
}