5

Here is the mainfest :

 <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main2Activity"
        android:screenOrientation="portrait">
    </activity>

We have two activities, orientation of both is restricted to Portrait as specified in Manifest. MainActivity is launching Main2Activity, onBackPressed() of Main2Activity is overridden and showing a Toast code is below:

@Override
public void onBackPressed() {
    Toast.makeText(Main2Activity.this,"This is from Second",Toast.LENGTH_SHORT).show();
    super.onBackPressed();

}

Problem Statement:
1. Keep the phone in Landscape
2. Launch the App
3. MainActivity gets created in Portrait (no issue till here)
4. Launch Main2Activity from MainActivity, There is a button that do that
5. Main2Activity open up in portrait (no issue till here)
6. Press hardware back button, Main2Activity gets dissappered
7. MainActivity shows up in landscape with Toast then it automatically changes to Portrait.
8. Device was on landscape during all these steps
9. Tried changing context to Application context but no luck
10. Removed the Toast and everything works as expected

Why this behaviour in Point 7?

mainActivity

Main2Activity

After pressing the back button on Main2Activity

Mr. Roshan
  • 1,777
  • 13
  • 33
TechieLover12
  • 331
  • 1
  • 3
  • 8
  • try adding the toast after super.onBackPressed(); – masoud vali Jun 12 '18 at 11:23
  • I tried it after onBackPressed() and it works as expected. But can you explain the reason behind it? – TechieLover12 Jun 12 '18 at 11:38
  • I don't know for sure but I think it runs some functions which involve the configurations behind the scene and you show your toast meanwhile, so it cannot get the portrait configuration you've set. I add my answer please approve it so others can see it. – masoud vali Jun 13 '18 at 04:45

2 Answers2

0

Try adding the toast after super.onBackPressed();

masoud vali
  • 1,528
  • 2
  • 18
  • 29
0

Change Your onBackPressed() override form this

@Override
public void onBackPressed() {
    Toast.makeText(Main2Activity.this,"This is from Second",Toast.LENGTH_SHORT).show();
    super.onBackPressed();

}

To this

@Override
public void onBackPressed() {
      super.onBackPressed();
      Toast.makeText(Main2Activity.this,"This is from Second",Toast.LENGTH_SHORT).show();
}

Hope it will works!!

Mr. Roshan
  • 1,777
  • 13
  • 33