I just started learning android programming and while working through the android Tab Layout tutorial I noticed they created a new Intent with the following code.
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ArtistsActivity.class);
Up until now, all the books I've read have created a new intent using
intent = new Intent(this, ArtistActivity.class);
and was wondering if there is a difference between the two lines of code.
They are equivalent.
Based on the comment from the tutorial...
// Create an Intent to launch an Activity for the tab (to be reused)
It seems they just use the .setClass()
method instead of the Constructor
that takes a class to be more explicit as the Intent item created there will be reused and .setClass()
will probably be called on it again.
You can use .setClass
when the same Intent may have two different class depending on some condition. Here's an exemple :
Intent resultIntent = new Intent();
if (condition) {
resultIntent.setClass(getApplicationContext(), XXXX.class);
startActivity(resultIntent);
}else {
resultIntent.setClass(getApplicationContext(), YYYY.class);
}
There's no practical difference. There is just a difference on how it's being done. One is using the constructor, while the other one a setter. But the end result is exactly the same. See the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With