Reputation:
I have created two activites MainActivity and Main2Activity. I want to launch Main2activity from MainActivity and also want to finish current activity and show a welcome toast. I am using this code
val intent = Intent(this,Main2Activity::class.java)
Toast.makeText(this,getString(R.string.welcome),Toast.LENGTH_LONG).show()
finish()
startActivity(intent)
so i have no problem but i need help when i run this code it works fine but Main2Activity take long to open and toast not shown for long when Main2Activity opens toast disappears in a few seconds so i think i have arrange the code wrong some one tell me how to arrange this code correctly. for example: finish first,toast second and then start activity.
Upvotes: 2
Views: 11835
Reputation: 957
try use this:
Intent intent = new Intent(this, NewActivity.class);
this.startActivity(intent);
Upvotes: 1
Reputation: 22832
It's better to do not leave a toast message with a finished activity. It may cause some problems like Screen Overlay Detected error. So, do this:
In MainActivity:
val intent = Intent(this, Main2Activity::class.java)
intent.putExtra("SHOW_WELCOME", true)
startActivity(intent)
finish()
In Main2Activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.getBooleanExtra("SHOW_WELCOME", false)) {
Toast.makeText(this, getString(R.string.welcome), Toast.LENGTH_LONG).show()
}
}
Upvotes: 4
Reputation: 164
There is one more approach to finish your current Activity and bring new one to the top.
val intent = Intent(this,Main2Activity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
Toast.makeText(this,getString(R.string.welcome),Toast.LENGTH_LONG).show();
startActivity(intent)
By the way, you can show toast like,
Toast.makeText(this,R.string.welcome,Toast.LENGTH_LONG).show()
You don't need to call getString(R.string.welcome)
Upvotes: 0
Reputation: 1098
If you arrange your code like this
val intent = Intent(this,Main2Activity::class.java)
Toast.makeText(this,getString(R.string.welcome),Toast.LENGTH_LONG).show()
startActivity(intent)
finish()
Then you will start your new activity and then you will finish your current activity. You still can some little delay between the changes but it's normal and you can add different animations so that users can feel smooth changes.
Upvotes: 0