Home > Back-end >  Return the app to starting point in the Android Studio
Return the app to starting point in the Android Studio

Time:04-18

I have created my first app in the android studio it is running well and I can randomly choose a picture. My intent is when it choose a picture I'd like it back to the start screen. I have tried the restart button but I do not know how to write the code.

'''

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

            val lemonOption: ImageView = findViewById(R.id.imageView)
            lemonOption.setOnClickListener{
            lemonChosen()
            }
         }
         private fun lemonChosen() {
             val lemon = Lemon()
             val chosenLemon = lemon.pick()
             val lemonOption: ImageView = findViewById(R.id.imageView)
             val resultTextView: TextView = findViewById(R.id.textView)
             if (chosenLemon != 1) {
             if(chosenLemon == 2){
                    resultTextView.text = "The Chosen lemon is the number 2"
             }else {
                resultTextView.text = "The Chosen lemon is the number 3"
                }
             } else {
                resultTextView.text = "The Chosen lemon is the number 1"
             }
             when (chosenLemon) {
                 1 -> lemonOption.setImageResource(R.drawable.limao_1)
                 2 -> lemonOption.setImageResource(R.drawable.limao_2)
                 3 -> lemonOption.setImageResource(R.drawable.limao_3)
                 }
              }
         }


     /**
       * The class lemon call the method to pick a lemon image determined randomized
      */
      class Lemon() {
          fun pick(): Int{
              return (1..3).random()
'''

CodePudding user response:

To restart your app ' Create an intent and start activity. Here flag is set to clear the top which means remove all the any other activities which are running in the app, this will prevent the multiple instances of the same activity as you want to reopen the same activity again.

val intent = Intent(this@MainActivity, MainActivity::class.java)
intent.flag = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)

CodePudding user response:

private fun restart() {
val lemonOption: ImageView = findViewById(R.id.imageView)
lemonOption.setImageResource(android.R.color.transparent)
}
  • Related