Android Intents, questions about setClass ()

I just started to learn programming in android and while working with the Android layout tutorial. I noticed that 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); 

So far, all books read have created a new intention, using

 intent = new Intent(this, ArtistActivity.class); 

and wondered if there is a difference between the two lines of code.

+6
source share
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) 

They seem to just use the .setClass() method instead of the Constructor , which makes the class more explicit, since the created Intent will be reused, and .setClass() will probably be called again on it.

+5
source

There is no practical difference. There is only a difference in how this is done. One uses a constructor, and the other uses a setter. But the end result is exactly the same. See the documentation.

+1
source

You can use .setClass when the same Intent can have two different classes depending on some condition. Here is an example:

  Intent resultIntent = new Intent(); if (condition) { resultIntent.setClass(getApplicationContext(), XXXX.class); startActivity(resultIntent); }else { resultIntent.setClass(getApplicationContext(), YYYY.class); } 
0
source

Source: https://habr.com/ru/post/889893/


All Articles