Reputation: 87
These are two intents which start another activity named StartActivity. They both run in different contexts but are not replaceable.
Intent intent = new Intent(MainActivity.this, StartActivity.class);
startActivity(intent);
and
Intent intent = new Intent(this, StartActivity.class);
startActivity(intent);
Upvotes: 1
Views: 55
Reputation: 44188
You only need to use MainActivity.this when there are multiple wrapping classes.
E.g.
public class MainActivity extends AppCompatActivity {
Runnable runnable = new Runnable() {
@Override
public void run() {
// this refers to the Runnable
// MainActivity.this refers to the activity
}
};
}
Upvotes: 0
Reputation: 1007624
You would see the first syntax when this code appears in an inner class of MainActivity
, such as the anonymous inner class implementation of View.OnClickListener
that you create for a setOnClickListener()
call. It says "the this
we want is the instance of MainActivity
, not the instance of the View.OnClickListener
implementation".
Upvotes: 5