开发者

Android Intents, questions about setClass()

开发者 https://www.devze.com 2023-03-10 15:03 出处:网络
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.

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 开发者_StackOverflowreused)
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消