Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Intents, questions about setClass()

Tags:

android

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.

like image 981
user786362 Avatar asked Jun 06 '11 18:06

user786362


3 Answers

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.

like image 131
Will Tate Avatar answered Nov 09 '22 15:11

Will Tate


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);
  }
like image 20
Galabyca Avatar answered Nov 09 '22 13:11

Galabyca


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.

like image 26
dmon Avatar answered Nov 09 '22 14:11

dmon