Search code examples
androidandroid-activitykotlin

Android screen flickering when starting an Activity


I am starting an activity with startActivityForResult() and sending an extra to it, then closing the second activity and going back to the previous one sending data back.

  • Only when launching the second activity (and not getting back to the first);

and

  • Only if the soft keyboard is open

and

  • Only on rooted devices or emulators,

This odd behavior happens.

I've tried the solutions posted here: Blinking screen on image transition between activities and here: Starting Activity on condition produces a flicker on screen with no success.

Here's the (trivial) code. Btw this (of course) happens either in Java or Kotlin (provided); and it also happens if I call startActivity() instead of startActivityForResult()

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_main.setOnClickListener { launchSecondActivity() }
    }

    private fun launchSecondActivity() {
        Intent(this, SecondActivity::class.java).run {
            putExtra(EXTRA_MESSAGE, editText_main.text.toString())
            startActivityForResult(this, RETURN_MESSAGE_CODE) 
            Log.d("MainActivity", "Sending ${this.extras}")
            // clean the editText
            editText_main.setText("")
        }
    }
}

Solution

  • When you launch the second activity keyboard is still visible and it is moving the layout up until it closes. Try following in your activity manifest

    <activity android:windowSoftInputMode="adjustResize"> </activity>

    adjustResize will not move toolbar up but resize the window height so hopefully screen won't flicker. If it does't help launch the activity with a delay to let keyboard close completely.